[英]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++? 现在,我有另一个类,该类持有对
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)
{}
};
// 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>
. 没有常见的
Base<Derived1>
和Base<Derived2>
基类。
You can introduce another class as a base of Base<T>
to pull off something that will be usable. 您可以引入另一个类作为
Base<T>
的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)
{}
};
That will be useful if you have virtual
member functions in RealBase
. 如果您在
RealBase
具有virtual
成员函数,这将很有用。 Otherwise, you'll have to use dynamic_cast
in client code for it to be useful. 否则,您必须在客户端代码中使用
dynamic_cast
才能使它有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.