简体   繁体   中英

reference data member to instantiations of template

I have a base class which is a template, and two derived classes like below,

template <class parm>
class Base{
};

class Derived1: public Base<Derived1>
{};

class Derived2: public Base<Derived2>
{};

Now I have another class holding a reference to Derived1 object or Derived2 object depending on which is passed into the constructor, but I don't know the syntax, is it achievable in 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)
  {}
};
 // 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; 

Given your class structure, that is not possible.

There is no common base class of Base<Derived1> and Base<Derived2> .


You can introduce another class as a base of Base<T> to pull off something that will be usable.

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

That will be useful if you have virtual member functions in RealBase . Otherwise, you'll have to use dynamic_cast in client code for it to be useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM