Mic*_*hel 6 c++ curly-braces initializer-list c++11
这个问题与这里讨论的问题有关.
我尝试使用初始化列表来创建要传递给的参数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"} ];
}
Run Code Online (Sandbox Code Playgroud)
我的编译器(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
Run Code Online (Sandbox Code Playgroud)
这应该是有效的C++ 11吗?
有趣的是,当使用operator()而不是operator[]它的工作.
是的,它是有效的 C++11,并且应该在任何兼容的编译器中工作。
请注意,gcc 中的 C++11 支持相当不成熟,并且此代码示例不会在任何 4.6 版本中编译,而只能在 4.7 svn snapshot 版本中编译。
| 归档时间: |
|
| 查看次数: |
643 次 |
| 最近记录: |