为什么 std::vector 不能采用本地类型?
void foo() {
struct Foo { .. };
std::vector<Foo> vec; // why is this illegal?
}
我不会把Foo送回外面的世界。它只是我在函数中使用的临时类型。
void foo() {
struct Foo { .. };
std::vector<Foo> vec; // why is this illegal?
}
I'm not returning Foo to the outside world. It's just a temporary type that I use within the function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
本地类不能作为模板参数。因为标准说:-
14.3.1 第 2 段:
“本地类型、无链接的类型、未命名类型或类型
由任何这些类型组成的化合物不得用作
模板类型参数的模板参数。”
建议一种解决方法 此处,关于 clc++.moderated。
更新:
关于为什么不能将本地类作为模板参数进行了一些讨论?链接 此处和此处 在 c.std.c++ 上讨论相同的内容。
A local class can't be a template argument. Because the standard says:-
14.3.1 paragraph 2:
"A local type, a type with no linkage, an unnamed type or a type
compounded from any of these types shall not be used as a
template argument for a template type parameter."
One workaround is suggested here on c.l.c++.moderated.
UPDATE:
There was some discussion on why is it not possible to have local-classes as template arguments? The links here and here on c.std.c++ discuss the same.
简短回答:
因为 C++ 标准是这么说的(
14.3.1
节)长答案:
在 C++ 标准化时,C++ 标准委员会认为会存在实现和性能问题。事实证明,这些担心是没有根据的,并且从 C++0x 标准的最终草案开始,他们已经撤销了这一决定。
更实际的是,一些编译器已经支持新的 C++0x 规则:
-std=c++0x
命令 gcc >=4.5 -行参数/Za
选项(禁用语言扩展)Short answer:
Because the C++ standard says so (section
14.3.1
)Long answer:
At the time that C++ was standardized, the C++ standards committee believed that there would be implementation and performance issues. Those fears turned out to be unfounded and, as of the final draft of the C++0x standard, they've reversed the decision.
On a more practical note, some compilers already support the new C++0x rules:
-std=c++0x
command-line parameter/Za
option (disable language extensions)