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?
}
我不会把 Foo 还给外面的世界。它只是我在函数中使用的一种临时类型。
本地类不能是模板参数。因为标准说:-
14.3.1 第 2 段:“本地类型、没有链接的类型、未命名类型或由这些类型中的任何一种复合的类型不得用作模板类型参数的模板参数。”
[Example:
template <class T> class X { /* ... */ };
void f()
{
struct S { /* ... */ };
X<S> x3; // error: local type used as templateargument
X<S*> x4; // error: pointer to local type used as templateargument
}
-end example] [Note: a template type argument may be an incomplete
type (3.9). ]"
在 clc++.moderated 上建议了一种解决方法。
更新:关于为什么不能将本地类作为模板参数进行了一些讨论?c.std.c++ 上的此处和此处的链接讨论了相同的内容。
简短的回答:
因为 C++ 标准是这样说的(部分14.3.1
)
长答案: 在 C++ 标准化的时候,C++ 标准委员会认为会有实现和性能问题。这些担心被证明是没有根据的,并且在 C++0x 标准的最终草案中,他们已经推翻了决定。
在更实际的情况下,一些编译器已经支持新的 C++0x 规则:
-std=c++0x
命令行参数/Za
(禁用语言扩展)