Question

Is it possible use in-explicit constructing with operators ?
Just like in this example (which does of course not work):

class myFoo {
    public:
        double x, y;

        myFoo(double, double);

        void    operator [] (myFoo);
};

int main() {
    myFoo f1(0.0, 1.1);
    f1[ {9.9, 10.0} ];          /// or whatever syntax to use, does not work
    f1.operator[] ( {9.9, 10.0} ); /// works !
}
Was it helpful?

Solution

C++11 allows an initializer list to be passed to an overloaded operator [] (see 13.5.5).

You'd need something like

void operator[](std::initializer_list<double>);

That would match your original syntax of f1[ {9.9, 10.0} ];.

OTHER TIPS

hmm...

f1[myFoo(9.9, 10.0)]; ?

requires a reasonably sane operator[] (i.e. expects a const myFoo& to bind to the temporary).

No this is not possible using operator [] in current C++03 or upcoming C++11 standard. However, you can exploit operator [] with some weird syntax to achieve the same:

f1[myFoo(9.9,10.0)];

where the operator [] is as,

myFoo& operator [] (const myFoo&);

yes it does work with the current code. Whatever might be your implementation with the '[]' (all I have done is to return the value at the index in an array inside a class. So the class can now be used as an array type) operator all that needs to be done to make sure that you pass in a const reference and make no changes are done.

int main() {
    myFoo f1(0.0, 1.1);
    f1[f1];      /// or whatever syntax to use
}

Will work.

Your code works fine in C++11 (g++ Version 4.5.2). You just have to say

f1[myFoo {9.9, 10.0} ];

instead of

f1[ {9.9, 10.0} ];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top