模板专业化和继承

Ama*_*eus 25 c++ inheritance templates c++11

假设我有一个包含许多函数的模板类,我想专门化它们只更改其中的一些,并保持其他完全按照基本模板类中的指定.

我怎样才能做到这一点?

下面是我想要实现的,但解决方案并不好,因为它不允许我引用intas的特化Base<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();
}
Run Code Online (Sandbox Code Playgroud)

输出是:

Base::print1
Base::print2
Base::print1
Base<int>::print2()
Run Code Online (Sandbox Code Playgroud)

mfo*_*ini 30

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;};
Run Code Online (Sandbox Code Playgroud)

这样你就可以只专门化特定的成员函数,并且仍然使用你没有专门的那些(在这种情况下print1)没有任何问题.所以现在你就像你想要的那样使用它:

Base<int> i;
i.print1();
i.print2(); // calls your specialization
Run Code Online (Sandbox Code Playgroud)

在这里演示.

  • @NicolBolas我相信§14.7.3/ 14允许这样做.我错了吗? (4认同)
  • 你确定这是标准的 C++ 还是编译器扩展? (2认同)

Nic*_*las 22

您只需使用两个模板类:

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;};
};
Run Code Online (Sandbox Code Playgroud)

你总是使用Base,而不是CommonBase.