美文网首页
C++:a template declaration is no

C++:a template declaration is no

作者: fck_13 | 来源:发表于2020-02-03 15:34 被阅读0次

我写了一段代码,想要测试一下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.

相关文章

网友评论

      本文标题:C++:a template declaration is no

      本文链接:https://www.haomeiwen.com/subject/fsvhxhtx.html