基于模板的成员初始化,其中模板是抽象类的派生
Template based member initialisation, where the template is a derivative of an abstract class
我正在研究一种遗传算法的实现,该算法应该适用于抽象的基因组类型。
我的设置是这样的:
class AbstractGenome
{
virtual void init() = 0;
virtual void mutate() = 0;
.
.
.
};
class GeneticAlgorithm
{
std::vector<AbstractGenome*> genomes;
void init(int numGenomes)
{
for (int i=0; i < numGenomes; ++i)
{
AbstractGenome *genome = new DerivedGenome(); <=This is where my problem is
genome->init();
genomes.push_back(genome);
}
}
}
其中DerivedGenome稍后(在某个时刻)定义为:
class DerivedGenome: public AbstractGenome
{
void init() { do stuff; }
void mutate() {do stuff; }
}
我的问题是,我对DerivedGenome唯一了解的是,它来源于AbstractGenome——因此,我无法对Derived Genome构造函数进行一般调用。
我能想到的解决这个问题的一种方法是从GeneticAlgorithm派生并覆盖所有基因组类型的init函数,但我想知道是否有更好的方法来解决这个问题,例如通过模板?
提前非常感谢。
您可以将DerivedGenome
类型传递到init()
:
template <typename Derived>
void init(int numGenomes)
{
for (int i=0; i < numGenomes; ++i)
{
AbstractGenome *genome = new Derived();
genome->init();
genomes.push_back(genome);
}
}
您可以通过以下方式拨打:
init<DerivedGenome>(42);
如果您想在尝试执行init<int>(5)
时出现更明确的编译错误,可以更改返回类型以要求继承:
template <typename Derived>
typename std::enable_if<
std::is_base_of<AbstractGenome, Derived>::value
>::type init(int numGenomes) { .. }
相关文章:
- 如何在从抽象基派生的类中实现相同的方法?
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 从从该抽象类派生的 Python 对象强制转换C++抽象类C++
- 两个抽象类,派生自同一个基类.如何访问从一个抽象类到另一个抽象类的指针
- 如何防止派生类成为 c++ 中的抽象类?
- 无法实例化抽象类,但类不是抽象/派生方法的参数
- 复制从抽象类派生的对象
- OOP - 抽象类类型,初始化基类和派生类中的变量
- 确保派生的类实现至少是来自抽象类(C )的两种方法之一
- 抽象类的需求是什么?为什么要通过其基类访问派生类方法?在C++
- 派生类使用的抽象类的方法
- 使用从WINRT网格类派生的抽象类时,Casttobase未解决的外部符号错误
- 基类的派生类,用作抽象类
- 多个"level"派生抽象类
- 尝试定义派生自抽象类的类类型的对象时出错
- 从抽象类派生的类的对象应在免费商店中
- C 带有嵌套类的抽象类.派生的类和嵌套类
- 在C++中从抽象类派生的类中没有销毁阶段
- 如果函数是从抽象类派生的,则不能用具体的类指针调用该函数
- 如何实例化从抽象类派生的类