【发布时间】:2015-06-12 16:46:34
【问题描述】:
我最近开始学习 c++。而且我有时会与模板专业化混淆。有人能告诉我为什么以下 No(3) 的模板专业化是非法的吗?
template<typename T> // No (1)
class ClassA {
public:
ClassA();
virtual ~ClassA();
void func(void);
};
template<> // No (2)
void ClassA<int>::func(void) {} // Ok legal specialization
template<typename T> // No (3)
void ClassA<int>::func(void) {} // error by compiler
似乎 No (3) 处的模板特化没有隐式模板参数,因为类型名 T 是 int。但是编译器给出以下错误,
error: prototype for ‘void ClassA<int>::func()’ does not match any in class ‘ClassA<int>’ void ClassA<int>::func(void) {
^
error: candidate is: void ClassA<T>::func() [with T = int] void func(void);
^
恐怕我在问一个愚蠢的问题,但我真的很想知道错误的原因。我想知道 1 号和 3 号的类型名 T 是否相同。请告诉我他们。非常感谢。
【问题讨论】:
-
(2) 和 (3) 都不应该编译
-
在 C++ 中,您通常会写成
func()而不是func(void)。后者只允许向后兼容 C。