The list of initializations as an argument to the operator []

This issue is related to the one discussed here .

I am trying to use a list of initializers to create an argument that needs to be passed to operator[] .

 #include <string> #include <vector> struct A { std::string& operator[](std::vector<std::string> vec) { return vec.front(); } }; int main() { // ok std::vector<std::string> vec {"hello", "world", "test"}; A a; // error: could not convert '{"hello", "world", "test"}' to 'std::vector...' a[ {"hello", "world", "test"} ]; } 

My compiler (GCC 4.6.1) complains:

 g++ -std=c++0x test.cpp test.cpp: In function 'int main()': test.cpp:20:8: error: expected primary-expression before '{' token test.cpp:20:8: error: expected ']' before '{' token test.cpp:20:8: error: expected ';' before '{' token test.cpp:20:35: error: expected primary-expression before ']' token test.cpp:20:35: error: expected ';' before ']' token 

Should this be valid C ++ 11?

Interestingly, when using operator() instead of operator[] it works.

+6
source share
1 answer

Yes, it is valid C ++ 11 and should work in any compatible compiler.

Note that C ++ 11 support in gcc is pretty immature, and this code example will not compile in any version 4.6, but only in snapshot versions of version 4.7 svn.

+4
source

Source: https://habr.com/ru/post/905507/


All Articles