看看这段代码:
struct foo {
virtual int bleh() {
return 42;
}
};
template<typename T>
struct bar : public foo {
};
// ERROR
template<>
int bar<char>::bleh() {
return 12;
}
我正在尝试提供 base::bleh
的定义仅适用于 bar<char>
, 但编译器 (gcc 4.7.2) rejects我的代码具有以下诊断:
template-id ‘bleh<>’ for ‘int bar<char>::bleh()’ does not match any template declaration
好像base::bleh
以某种方式隐藏在 bar
中.我已经使用 bar
中的以下定义修复了此问题:
template<typename T>
struct bar : public foo {
// doesn't work
//using foo::bleh;
// this works
int bleh() {
return foo::bleh();
}
};
但我很好奇为什么编译失败。为什么编译器拒绝我的代码?
最佳答案
在您的非编译示例中,您试图专门化和定义一个尚未在 bar
的模板定义中声明的函数......在您后面的示例中,您实际上已经声明了以及在 bar
的模板定义中定义函数的非专用版本,这就是它编译的原因。据我所知,这是标准中有关第一个版本无法编译 (14.7.3/4) 的原因的相关语言:
A member function, a member function template, a member class, a member enumeration, a member class template, or a static data member of a class template may be explicitly specialized for a class specialization that is implicitly instantiated; in this case, the definition of the class template shall precede the explicit specialization for the member of the class template
关于c++ - 在派生类模板中专门化基类的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16473499/