【问题标题】:Template based member initialisation, where the template is a derivative of an abstract class基于模板的成员初始化,其中模板是抽象类的派生
【发布时间】:2015-04-17 13:02:45
【问题描述】:

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

我的设置是这样的:

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 - 因此我无法对 DerivedGenome 构造函数进行一般调用。

我能想到解决这个问题的一种方法是从遗传算法派生并覆盖所有基因组类型的 init 函数,但我想知道是否有更好的方法来解决这个问题,例如通过模板?

提前非常感谢。

【问题讨论】:

  • ...究竟是什么问题?
  • 好点。查看我的编辑。

标签: c++ class templates


【解决方案1】:

您可以将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&lt;int&gt;(5),您可以更改返回类型以要求继承:

template <typename Derived>
typename std::enable_if<
    std::is_base_of<AbstractGenome, Derived>::value
>::type init(int numGenomes) { .. }

【讨论】:

  • 非常感谢。这几乎是我希望拥有的。
  • 我已经尝试过你的建议,但我不太确定该怎么做:架构 x86_64 的未定义符号:“void NSGAII::init(unsigned int)”,引用自: _main in main.o 我已经根据您的建议明确定义了我的 NSGAII::init
猜你喜欢
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
  • 2012-09-12
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 2011-03-14
相关资源
最近更新 更多