C ++ 14警告:变量的模板头太多(应为0) [英] C++14 warning: too many template headers for variable (should be 0)

查看:92
本文介绍了C ++ 14警告:变量的模板头太多(应为0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试使用最新的g ++-5编译器时,我在文件中写了以下语句:

While experimenting with the recent g++-5 compiler, I wrote below statement in a file:

template<T> T a;
template<> int a = 1;

这将导致:

警告:a的模板标头过多(应为0)

warning: too many template headers for a (should be 0)

同样有效的是,它实际上并没有专门研究a<int>.例如

Also effectively, it doesn't really specialize a<int>. e.g.

template<typename T> T a;
template<> int a = 1;

int main ()  {
  std::cout << a<double> << "\n";  // prints 0; OK
  std::cout << a<int> << "\n";  // prints 0! why not 1?
}

有关此语法的奥秘是什么?

What is the mystery about this syntax?

推荐答案

模板参数只能在 function 模板的显式专门化中省略.您有一个变量模板,因此必须包含<int>:

Template arguments can only be omitted in explicit specialisation of function templates. You have a variable template, so you have to include the <int>:

template<> int a<int> = 1;

引用C ++ 14(n4140),14.7.3/10(重点是我):

Quoting C++14 (n4140), 14.7.3/10 (emphasis mine):

template-id 中可以不指定尾随的 template-argument ,命名一个明确的功能模板 ,前提是可以从函数参数类型推导出来.

A trailing template-argument can be left unspecified in the template-id naming an explicit function template specialization provided it can be deduced from the function argument type.

如果不想重复输入,可以使用auto:

If you do not want to repeat the type, you can use auto:

template<> auto a<int> = 1;

[实时示例] 使用Clang.

请记住以下几点:使用auto时,将根据初始化程序而不是模板参数推导出专用变量的类型.而且由于专业化可以具有与主模板不同的类型,因此即使它们不同,编译器也会很乐意接受它.

There's one thing to bear in mind with this: when using auto, the type of the specialised variable will be deduced from the initialiser, not from the template argument. And since a specialisation can have a different type than the primary template, the compiler will happily accept it even if they differ.

这篇关于C ++ 14警告:变量的模板头太多(应为0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆