初始值设定项列表作为运算符[]的参数
initializer list as argument to operator[]
这个问题与这里讨论的问题有关。
我尝试使用初始值设定项列表来创建一个要传递给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+"必须采用零个或一个参数
- 为什么数组大小信息可用于"sizeof"运算符和 delete[] 运算符,但在将数组作为参数传递到
- 参数相关查找和流运算符重载
- C++:使用运算符 = 调用多参数构造函数
- 了解布尔运算符==(参数 1,参数 2)
- 我能否根据其运算符()的签名专门化可变参数模板参数
- SFINAE 检查模板参数运算符
- 不允许运算符 const 参数调用 const 成员函数
- 为私有结构定义双参数运算符重载
- C++ 通过自定义赋值运算符隐式转换函数参数
- 函数参数变量总是需要 & 或 * 运算符吗?
- 算术运算符参数类型
- 隐式转换以匹配运算符参数
- 对重载运算符参数执行隐式转换时出现编译器错误
- 避免在C++中强制转换运算符参数
- 如果给定模板不是运算符参数类型的专用模板,则禁用运算符重载
- 以及C++中的运算符参数求值
- 这个函数的运算符参数太多