我有一个基类,它是一个模板,以及两个派生类,如下所示,
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)
{}
};
答案 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
才能使用它。