我写了一段代码,想要测试一下C++ 11的一些type traits
。
TEST(cpp11_library_feature, type_traits)
{
template<typename> //error:a template declaration is not allowed here
struct PM_traits {};
...
}
错误提示告诉我我不能够再这里使用template
。通过搜索,找到了以下内容:
- C++ 标准说:
Template declarations are only permitted at global, namespace, or class scope.
翻译过来就是说template
只能在全局,命名空间和类内声明。而我将其声明在了函数内部,所以爆出了这个问题。
对于这个问题,比较直观的例子应该是
void func()
{
template<class>
class A {}
}
- 进一步搜索得到:
对于template
的实现,需要template
中的所有符号都能够被外部链接。而在函数内定义的名字是是没有链接属性的,不能被外部访问到。
The problem is probably linked to the historical way templates were implemented: early implementation techniques (and some still used today) require all symbols in a template to have external linkage. (Instantiation is done by generating the equivalent code in a separate file.) And names defined inside a function never have linkage, and cannot be referred to outside of the scope in which they were defined.
网友评论