假设我有一个拥有许多函数的模板类,我想对其中的一些函数进行特化,但仍保持其他函数与基础模板类中指定的完全相同。
我该如何实现这个目标?
下面是我想要实现的内容,但解决方案并不好,因为它不能让我使用 Base<int>
来引用 int
的特化版本 - 我需要使用 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();
}
输出结果为:
Base::print1
Base::print2
Base::print1
Base<int>::print2()