引用数据成员到模板的实例化

时间:2017-06-26 22:17:23

标签: c++ c++11

我有一个基类,它是一个模板,以及两个派生类,如下所示,

template <class parm>
class Base{
};

class Derived1: public Base<Derived1>
{};

class Derived2: public Base<Derived2>
{};

现在我有另一个类,其中包含对Derived1对象或Derived2对象的引用,具体取决于传递给构造函数的对象,但我不知道语法,是否可以在C ++中实现?

struct Observer{

  // I want to hold a reference to Derived1 or Derived2 based on 
  // which is passed into the constructor
  template <class parm>
  Base<parm> & derived_reference;

  Observer(Derived1 & d1):derived_reference(d1) // what's the right syntax here?
 {}

  Observer(Derived2 & d2):derived_reference(d2)
  {}
};

1 个答案:

答案 0 :(得分:1)

// I want to hold a reference to Derived1 or Derived2 based on 
// which is passed into the constructor
template <class parm>
Base<parm> & derived_reference;

鉴于你的班级结构,这是不可能的。

没有Base<Derived1>Base<Derived2>的共同基类。

您可以引入另一个类作为Base<T>的基础来推出可用的东西。

struct RealBase { virtual ~RealBase() {} };

template <class parm>
class Base : public RealBase {};

class Derived1: public Base<Derived1>
{};

class Derived2: public Base<Derived2>
{};

struct Observer{

   RealBase& derived_reference;

   Observer(Derived1& d1):derived_reference(d1)
   {}

   Observer(Derived2& d2):derived_reference(d2)
   {}
};

如果virtual中有RealBase个成员函数,那将非常有用。否则,您必须在客户端代码中使用dynamic_cast才能使用它。