gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:05:59 24 4
gpt4 key购买 nike

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

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

最佳答案

// 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;

鉴于您的类(class)结构,这是不可能的。

Base<Derived1> 没有公共(public)基类和 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在客户端代码中使用它。

关于c++ - 引用数据成员到模板的实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44769474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com