代码:
template<class T>
struct A {
void f1() {};
void f2() {};
};
template<>
struct A<int> {
void f2() {};
};
int main() {
A<int> data;
data.f1();
data.f2();
};
错误:
test.cpp: In function 'int main()':
test.cpp:16: error: 'struct A<int>' has no member named 'f1'
基本上,我只想特化一个函数,而对其他函数使用通用定义。 (在实际代码中,我有很多我不想专门化的函数)。
如何做到这一点?谢谢!
最佳答案
考虑将公共(public)部分移动到基类:
template <typename T>
struct ABase
{
void f1();
};
template <typename T>
struct A : ABase<T>
{
void f2();
}
template <>
struct A<int> : ABase<int>
{
void f2();
};
您甚至可以在派生类中覆盖 f1
。如果您想做一些更奇特的事情(包括能够从基类中的 f1
代码调用 f2
),请查看 CRTP .
关于c++ - 如何专门化模板类的某些成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4955609/