简体   繁体   中英

initializer list as argument to operator[]

This question is related to the one discussed here .

I try to use an initializer list to create an argument 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM