سؤال

Currently, we can only overload operator[] with exactly one argument.

I would like to know if there is a fundamental reason why the standard does not allow to overload operator[] for several arguments ?

Are there propoposals in this way for C++17 ?

هل كانت مفيدة؟

المحلول

This probably could be added, but shouldn't, because it breaks existing code.

Basically, what multiple arguments to operator[] would mean is that the following would compile:

struct Foo
{
    int operator[](int a, int b, int c)
    {
        return 0;
    }
}

int main()
{
    Foo foo;
    auto n = foo[1, 2, 3]; // list of parameters
}

However consider this:

int main()
{
    Foo foo;
    std::vector<int> bar(4, 0);
    auto n = foo[1, 2, 3]; // list of parameters
    auto x = bar[1, 2, 3]; // comma operator! returning the 3rd element of bar. valid syntax
}

This would mean, that in an expression using comma inside of square brackets can either be a list of parameters or the use of the comma operator. Therefore, there could only ever be exactly one valid number for the arguments of operator[], meaning this couldn't be resolved:

struct Foo
{
    int operator[](int a, int b, int c)
    {
        return 0;
    }
    int operator[](int a)
    {
        return 1;
    }
}

There is no way to dissolve the ambiguity of 1, 2, 3 here. This means: if the standard would change to allow this, any code using the comma operator in calls to operator[] would become a compile error. The standard commitee tries hard to not break existing code (which is a good thing!) with the introduction of new features. In my opinion, this would be quite a radical change and is therefore unlikely to be done.

If you want multiple arguments, either use a different operator (as Mike suggested, operator() would work) or pass a std::tuple or equivalent.

نصائح أخرى

I would like to know if there is a fundamental reason why the standard does not allow to overload operator[] for several arguments ?

No fundamental reason; just the general principle that overloaded operators have the same syntax as the built-in operator they overload.

Are there propoposals in this way for C++17 ?

No. A common alternative is to overload operator(); that can take as many arguments as you like.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top