初始化列表作为操作符[]的参数
此问题与此处讨论的问题相关。
我尝试使用初始值设定项列表来创建要传递给 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[]
时,它可以工作。
This question is related to the one discussed here.
I try to use an initializer list to create an argument to be passed to 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"} ];
}
My Compiler (GCC 4.6.1) complains:
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
Should this be valid C++11?
Interestingly, when using operator()
instead of operator[]
it works.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,它是有效的 C++11,并且应该在任何兼容的编译器中工作。
请注意,gcc 中的 C++11 支持相当不成熟,并且此代码示例不会在任何 4.6 版本中编译,而只能在 4.7 svn snapshot 版本中编译。
Yes, it is valid C++11 and should work in any compliant compiler.
Please note that C++11 support in gcc is quite immature, and this code example will not compile in any 4.6 version, but only in 4.7 svn snapshot versions.
是的,它是有效的。您使用的 GCC 版本尚未完全支持 C++11,因此即使符合标准,也无法编译。
更新版本的 GCC 可以编译您的代码。
请参阅编译器资源管理器中的实时示例。
Yes, it is valid. The version of GCC you're using doesn't have full support for C++11 yet, so it fails to compile, even when it's standard-compliant.
A more recent version of GCC compiles your code.
See live example at Compiler Explorer.