c++ - 初始化列表作为 operator[] 的参数

标签 c++ c++11 curly-braces initializer-list

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

我尝试使用初始化列表来创建要传递给 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[] 时它起作用了。

最佳答案

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

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

关于c++ - 初始化列表作为 operator[] 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8786927/

相关文章:

c++11 - 无法运行 move 构造函数

c++ - 复制构造函数问题李普曼

c++ - 为什么预处理器宏是邪恶的,有哪些替代方案?

syntax - Prolog 中大括号的含义

c++ - map 没有为自定义结构命名模板类型

c++ - 当 [] 运算符失败并且我需要对此断言时会发生什么?

c# - 使用 Roslyn-CTP 的单个右括号的奇怪解析行为

c++ - 抛出 'std::out_of_range' 实例后调用终止

c++ - 使用脚本调用时 RapidXML 不解析

c++ - 访问默认 lambda 参数中的模板类参数