Reputation: 3260
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)
{}
};
Upvotes: 0
Views: 41
Reputation: 206627
// 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.
Upvotes: 1