模板专业化和继承 [英] Template specialization and inheritance

查看:108
本文介绍了模板专业化和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个有很多函数的模板类,我想专门改变它们中的几个,并保持其他的完全一样的基本模板类中指定。



我该如何做?



下面是我想实现的,但是解决方案不好,因为它不允许我请参考 int 的专业化为 Base –我需要使用 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>一世; < - 我想这种实例化
IntSpec i;

d.print1();
d.print2();
i.print1();
i.print2();
}

输出为:

  Base :: print1 
Base :: print2
Base :: print1
Base< int> :: print2()


解决方案

Nicol的解决方案很好,但这是一个替代方案:

  template< typename T> 
struct Base
{
void print1(){cout< Base :: print1< endl;};
void print2(){cout<< Base :: print2< endl;};
};

模板<>
void Base< int> :: print2(){cout< Base< int> :: print2()<< endl;};

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

  Base< int>一世; 
i.print1();
i.print2(); // call your specialization

演示这里


Suppose I have a template class with a lot of functions and I want to specialize them to change only a few of them and keep the other ones exactly as specified in the base template class.

How can I do that?

Below is what I want to achieve, but the solution isn't good, because it does not allow me to refer to the specialization for int as Base<int> – I need to use IntSpec for that.

#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();
}

The output is:

Base::print1
Base::print2
Base::print1
Base<int>::print2()

解决方案

Nicol's solution works fine, but this is an alternative:

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;};

That way you can specialize only specific member functions and still use those that you haven't specialized(in this case, print1) without any problem. So now you'd use it just like you wanted:

Base<int> i;
i.print1();
i.print2(); // calls your specialization

Demo here.

这篇关于模板专业化和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆