假设我有一个包含很多函数的模板类,我想专门化它们只改变其中的一些,并保持其他的完全按照基本模板类中的指定。
我该怎么做?
以下是我想要实现的目标,但解决方案并不好,因为它不允许我将int
的专业化称为Base<int>
- 我需要使用{{1为此。
IntSpec
输出结果为:
#include <iostream>
using namespace std;
template<typename T>
struct Base
{
void print1() {cout << "Base::print1" << endl;};
void print2() {cout << "Base::print2" << endl;};
};
struct IntSpec : public Base<int>
{
void print2() {cout << "Base<int>::print2()" << endl;};
};
int main()
{
Base<double> d;
// Base<int> i; <-- I want this kind of instantiation
IntSpec i;
d.print1();
d.print2();
i.print1();
i.print2();
}
答案 0 :(得分:27)
Nicol的解决方案运行良好,但这是另一种选择:
template<typename T>
struct Base
{
void print1() {cout << "Base::print1" << endl;};
void print2() {cout << "Base::print2" << endl;};
};
template<>
void Base<int>::print2() {cout << "Base<int>::print2()" << endl;};
通过这种方式,您可以专门使用特定的成员函数,并且仍然可以使用那些您没有专门的成员函数(在这种情况下,print1
),没有任何问题。所以现在你就像你想要的那样使用它:
Base<int> i;
i.print1();
i.print2(); // calls your specialization
演示here。
答案 1 :(得分:20)
您只需使用两个模板类:
template<typename T>
struct CommonBase
{
void print1() {cout << "Base::print1" << endl;};
void print2() {cout << "Base::print2" << endl;};
};
template<typename T>
struct Base : public CommonBase<T>
{
};
template<>
struct Base<int> : public CommonBase<int>
{
void print2() {cout << "Base::print2" << endl;};
};
您始终使用Base
,而不是CommonBase
。
答案 2 :(得分:4)
另一种解决方案是在要重新定义的函数中添加一个间接级别,即
template<typename T>
struct foo
{
template<typename T2>
void bar_impl()
{
//generic function
}
void bar()
{
bar_impl<T>();
}
};
然后,您可以为每种类型单独指定每个功能,或者根据需要专门化整个类型。