C++ 初始值设定项列表作为运算符[]的参数

C++ 初始值设定项列表作为运算符[]的参数,c++,c++11,curly-braces,initializer-list,C++,C++11,Curly Braces,Initializer List,这个问题与讨论的问题有关 我尝试使用初始值设定项列表创建要传递给运算符[]的参数 #include <string> #include <vector> struct A { std::string& operator[](std::vector<std::string> vec) { return vec.front(); } }; int main() { // ok std::vector<std::string

这个问题与讨论的问题有关

我尝试使用初始值设定项列表创建要传递给
运算符[]
的参数

#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"} ];
}
这应该是有效的C++11吗


有趣的是,当使用
operator()
而不是
operator[]
时,它可以工作。

是的,它是有效的C++11,应该可以在任何兼容的编译器中工作


请注意,gcc中对C++11的支持非常不成熟,这个代码示例将不会在任何4.6版本中编译,而只在4.7 svn快照版本中编译。

最明确的是,这是编译器错误,因为
a.f({“aa”,“bb”})
a[{“aa”,“bb”}]
。传递一个临时变量会显式编译:
a[std::vector({“hello”,“world”,“test”})使用svn主干版本179769中的GCC4.7也不起作用。与GCC4.6的错误报告相同。@MichelSteuwer:在发布这篇文章之前,我尝试了GCC4.7的本地版本r182904(我想),并且成功了。
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