从非模板类派生的模板类:访问派生类的泛型变量
Template class derived from nontemplate class: access to derived class' generic variable
已解决
我想使用模板创建一个不同类型对象的数组。因此,我有一个非模板类(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;
};
相关文章:
- 错误处理.将系统错误代码映射到泛型
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 链表的泛型函数remove()与成员函数remove)
- 给定一个类型,如何派生一个泛型更广泛的类型(例如,用于溢出安全求和)?
- 模板化接口 - 创建一个泛型模板类以返回任何容器
- 如何编写将要继承的泛型代码?
- C++17 如何保存泛型可调用对象以供以后使用
- 使用宏扩展的泛型:为什么指令缓存使用不当?
- C++泛型类错误,问题出在哪里?
- C++泛型类,单独实现?
- 将参数传递给泛型 lambda 时复制构造函数不正确
- 从具有泛型返回类型的 crtp 基类调用派生类中的函数
- boost::serialization-序列化从泛型属性/功能容器派生的类
- 如何从虚拟函数返回泛型派生类
- 在泛型编程中,需要在派生类中重新声明基类成员函数
- 使用基类的泛型方法指针调用派生类的方法
- C++泛型编程 CRTP 基类继承自派生类型提供的类
- 用于初始化派生类型的泛型 switch 语句
- 从非模板类派生的模板类:访问派生类的泛型变量
- 从派生类中的强制转换泛型指针访问成员会导致访问冲突