基于模板的成员初始化,其中模板是抽象类的派生

Template based member initialisation, where the template is a derivative of an abstract class

本文关键字:抽象类 派生 于模板 成员 初始化      更新时间:2023-10-16

我正在研究一种遗传算法的实现,该算法应该适用于抽象的基因组类型。

我的设置是这样的:

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