2009-09-12 1338 views
20

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

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

} 

测试案例1:

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

} 

测试案例2:

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

} 

生成以下编译错误:

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

有谁知道为什么?

+0

你在使用什么平台/编译器? – aaa90210 2009-09-12 22:57:03

+0

我正在使用Visual C++ 08 – jameszhao00 2009-09-13 01:23:45

回答

51

函数模板不能部分专用,只有充分,即这样的:

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

} 

为什么函数模板不能部分专业,你可能要read this

当你专注部分(仅适用于类),你必须那样做:

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

}; 

所以必须再次列出T1

你的专业化写作方式,他们会模糊spec1<int, int>

+3

啊所以我可以有部分专用类嵌入静态功能? – jameszhao00 2009-09-13 01:24:33

+0

哦,我看到你链接的文章已经解释了问题。我删除了我的答案,因为我发现在这种情况下转发到一个班级更方便。在使用'T1'和'T2'作为函数参数类型的情况下,我发现重载更可读,因为它就像正常函数重载那样。 – 2009-09-13 02:18:33

+0

当我读到“只能上课时”时,我b。不安。我发现对于类和结构都是可能的;-)。 – 2014-04-17 15:26:38