一个直接的解决方案是,定义包含您想要专门化的东西的基类模板,然后专门化这个类模板(毕竟这将是一个小类):
template<typename T>
struct printable
{
protected:
void print(const T & _t) { }
};
template<>
struct printable<double>
{
protected:
void print(const double & _t) { }
};
然后从中得出:
template<typename T>
class MyClass : public printable<T>
{
typedef printable<T> base;
public:
MyClass(T t&):_t(t){}
~MyClass(){}
void print(){ base::print(_t); } //forward
private:
T _t;
};
您不再需要专门化此类模板;让它尽可能大(并且合理)。
另一种选择是基于策略的设计,其中您将策略类作为模板参数传递给您的类模板(称为主机类)。
例如,
//lets define few policy classes
struct cout_print_policy
{
template<typename T>
static void print(T const & data)
{
std::cout << "printing using cout = " << data << std::endl;
}
};
struct printf_print_policy
{
static void print(int data)
{
std::printf("printing int using printf = %d\n", data);
}
static void print(double data)
{
std::printf("printing double using printf = %f\n", data);
}
};
//now define the class template (called host class) that
//accepts policy as template argument
template<typename T, typename TPrintPolicy>
class host
{
typedef TPrintPolicy print_policy;
T data;
public:
host(T const & d) : data(d) {}
void print()
{
print_policy::print(data);
}
};
测试代码:
int main()
{
host<int, cout_print_policy> ic(100);
host<double, cout_print_policy> dc(100.0);
host<int, printf_print_policy> ip(100);
host<double, printf_print_policy> dp(100.0);
ic.print();
dc.print();
ip.print();
dp.print();
}
输出:
printing using cout = 100
printing using cout = 100
printing int using printf = 100
printing double using printf = 100.000000
在线演示:http: //ideone.com/r4Zk4