函数的 C++ 模板特化:“非法使用显式模板参数”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1416345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:53:11  来源:igfitidea点击:

C++ template specialization of function: "illegal use of explicit template arguments"

c++templatestemplate-specializationtypename

提问by jameszhao00

The following template specialization code:

以下模板特化代码:

template<typename T1, typename T2>
void spec1()
{

}

Test case 1:

测试案例1:

template< typename T1> //compile error
void spec1<int>()
{

}

Test case 2:

测试案例2:

template< typename T2> //compile error
void spec1<int>()
{

}

generates the following compilation error:

生成以下编译错误:

error C2768: 'spec1' : illegal use of explicit template arguments

错误 C2768:“spec1”:非法使用显式模板参数

Does anyone know why?

有谁知道为什么?

回答by Rüdiger Hanke

Function templates cannot be partially specialised, only fully, i.e. like that:

函数模板不能部分特化,只能完全特化,例如:

template<>
void spec1<char, int>()
{

}

For why function templates cannot be partially specialised, you may want to read this.

关于为什么函数模板不能部分专门化,你可能需要阅读这个

When you specialise partially (only possible for classes), you'd have to do it like that:

当您部分专业化(仅适用于类)时,您必须这样做:

template <typename T1>
class class1<T1, int>
{

};

so you have to list T1again.

所以你必须T1再次列出。

The way your specialisations are written, they would be ambiguous for spec1<int, int>.

您的专业化的编写方式,对于spec1<int, int>.