问题描述
在尝试使用最新的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<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):
如果不想重复输入,可以使用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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!