首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模板与多态性

模板与多态性
EN

Stack Overflow用户
提问于 2019-05-06 15:25:26
回答 1查看 132关注 0票数 0

我正在为遗传算法/神经进化写一个库。目前,该程序使用多态性允许多种类型的基因组。所以我的代码是这样的:

代码语言:javascript
复制
class Genome { // Interface
    // Some abstract functions 
}

class SpecificGenome : public Genome {
    // implementation
public:   
    int do_something(int x); // Specific behavior, which only this SpecificGenome has
}

class Population {
public:
    Population(size_t population_size, std::function<std::unique_ptr<Genome>()> create_genome);
    // Some functions
    std::vector<std::unique_ptr<Genome>> members;
}

std::unique_ptr<Genome> create_specific_genome(){
    return std::unique_ptr<Genome>(std::make_unique<SpecificGenome>());
}

int main() {
    Population p(150, &create_specific_genome);

    int y = static_cast<SpecificGenome>(*p.members[0].get())->do_something(4);
}

我正在考虑改变它,这样它就会使用模板而不是多态,因为每个基因组都编码一个物状体,它可以有任何类型的行为,与其他的物状体类型没有任何共同之处,有些基因组使用直接的编码方案,不需要被解码成一个小体。因此,每个基因组都必须由用户向他相应的子类投射,才能揭露它的行为,这看起来非常丑陋。问题是基因组的每个子类都是--基因组,需要有一些特定的功能才能工作,所以多态性是非常有意义的。

编辑:的问题,因为它现在是非常不清楚,所以我想补充一些解释。我希望能够创建任何类型的基因组(NeuralNetwork,Interface,一个图像,.),所以我使用一个接口和子类来实现这一点,这样种群中的向量就可以使用一个基因组指针来存储每个类型。这是有用的,因为每个基因组类型需要有特定的方法,如交叉和突变。问题出现了,当我想要使用特定的函数,比如计算神经网络的输出,基因组解码或者获取图像的像素数据,基因组解码。这让我怀疑使用模板而不是继承是否更好。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-06 16:33:09

模板可能更好地帮助您的情况,但有其他的含义。

例如,列表中包含的基因组类型不能是异构的。肯定是同一种类型的。如果您需要异源性,那么您将不得不实现某种类型的擦除。

下面是一个示例,它看起来很像您的示例,但是具有静态多态性:

代码语言:javascript
复制
// no inheritance
class SpecificGenome {
public:   
    int do_something(int x);
}

template<typename G, typename C>
class Population {
public:
    Population(size_t population_size, C create_genome);

    // no need for pointers. Values work just fine.
    std::vector<G> members;
}

// Deduction guide using the create_genome function return type
template<typename C>
Population(std::size_t, C) -> Population<std::invoke_result_t<C>, C>;

SpecificGenome create_specific_genome() {
    return SpecificGenome{};
}

int main() {
    // Uses class template argument deduction
    Population p(150, create_specific_genome);

    int y = p.members[0].do_something(4);
}

顺便说一句,如果您仍然使用std::unique_ptr,那么您可以用更好的语法来使用它:

代码语言:javascript
复制
std::unique_ptr<Genome> create_specific_genome() {
    // no need for casts
    return std::make_unique<SpecificGenome>();
}

// no need for calls to `get`.
int y = static_cast<SpecificGenome&>(*p.members[0]).do_something(4);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56008187

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档