将初始化列表作为operator[]的参数

7
这个问题与此处讨论的问题有关
我尝试使用初始化列表创建一个参数,以传递给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"} ];
}

我的编译器(GCC 4.6.1)报错:

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

这段代码是否符合C++11标准?

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


1
绝对没错,这肯定是编译器的bug,因为a.f({"aa", ""bb"})a[{"aa", ""bb"}]之间绝对没有任何区别。 - Nawaz
传递一个临时变量会被显式编译,例如:a[ std::vector<std::string>({"hello", "world", "test"}) ]; - jrok
2个回答

4

是的,它是有效的C++11代码,可以在任何符合标准的编译器上运行。

请注意,gcc中对C++11的支持还比较不成熟,在任何4.6版本中都无法编译此代码示例,只能在4.7 svn快照版本中编译。


使用来自svn主干修订版号179769的GCC 4.7也无法工作。与GCC 4.6相同的错误报告。 - Michel
@MichelSteuwer:在发布之前,我尝试使用我的本地构建的gcc 4.7(我想是r182904),它可以工作。 - PlasmaHH

0
是的,它是有效的。你正在使用的GCC版本对C++11的支持还不完整,所以即使它符合标准,它也无法编译通过。
较新版本的GCC可以编译你的代码。 请参考Compiler Explorer上的实时示例

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接