从非模板类派生的模板类:访问派生类的泛型变量

Template class derived from nontemplate class: access to derived class' generic variable

本文关键字:派生 泛型 变量 访问      更新时间:2023-10-16

已解决

我想使用模板创建一个不同类型对象的数组。因此,我有一个非模板类(Base),以及一个从基类派生的模板类。

我想知道的是如何访问派生类的泛型值(T val)?

class Base{
public:
    // a function returns T val, it will be implemented in Derived class
    // EDIT : virtual function here
};
template<class T>
class Derived: public Base {
public:
    T val;
    Derived(T x) {
        val = x;
    }
    // implementation.. it returns val
    // EDIT : Implementation of virtual function
};

解决方案:dynamic_cast,注意基类应该至少有一个虚拟函数。

Base *p[2];
p[0] = new Derived<int>(24);
p[1] = new Derived<double>(82.56);
int a = dynamic_cast<Derived<int>*>(p[0])->val;        // casts p[0] to Derived<int>*
double b = dynamic_cast<Derived<double>*>(p[1])->val;  // casts p[1] to Derived<double>*
cout << a << endl; 
cout << b << endl;

上次我检查时,您不能从基类(非虚拟)访问派生类成员。

您可以通过这种方式修改代码,因为您使用的是模板。类型和值在构造时传递给基类,然后您可以使用它

template<typename T>
class Base {
   T ini;
public:
    Base(T arg){ini = arg;}
    T ret(){return ini;}
};
template<class T>
class Derived: public Base<T> {
public:
    T val;
    Derived(T x) : Base<T>(x) {
        //Base(x);
        val = x;
    }
    // implementation.. it returns val
};

然后你可以像往常一样实例化它并使用它

Derived<int>  e(5);    
e.ret();

看起来你想要CRTP

其思想是访问基类内部的派生类成员。请注意,您将无法包含它们的异构列表。

template<typename D>
struct Base {
    void doThings() {
        // access the derived class getT function
        auto var = static_cast<D&>(*this).getT();
        cout << var << endl;
    }
};
template<typename T>
struct Derived : Base<Derived> {
    T getT() {
        return myT;
    }
private:
    T myT;
};