gpt4 book ai didi

c++ - 模板化唯一指针

转载 作者:行者123 更新时间:2023-11-30 03:15:22 25 4
gpt4 key购买 nike

我是 C++ 的新手。

我有一个名为 Main_Alg 的类,它运行(通用)主算法。我有不同的类与基类 Calc_Type 和两个派生类说类 A 和类 B

Main_Alg 创建时,run 将运行通用算法,使用方法 solve AB(在 Calc_Type 中是纯虚拟的)。执行哪一个由用户指定。

实现此目标的最佳方法是什么?

我想到了一个模板类Main_alg:

if (parms == "A"){
std::unique_ptr<Main_Alg<A>> main_alg(new Main_alg<A>);
main_alg -> run;
}
else ... // for B or whatever

运行中:

std::unique_ptr<T> method;
method -> solve;
method -> getsmthg; //method only implemented for base class Calc_type `

这会使事情过于复杂吗?这是好习惯吗?也欢迎任何阅读建议

最佳答案

如果您是 C++ 新手,请不要编写自己的模板。它们很酷,但很难掌握,尤其是当您开始使用 C++ 编写代码时。

您已经写了一些关于纯虚拟类的内容。如果有,则不需要模板。

class Calc_Type {
virtual ~Calc_Type() {}
virtual void run() = 0;
};

class A : public Calc_Type {
public:
void run() override {
stuff_to_do();
}
};

class B : public Calc_Type {
public:
void run() override {
other_stuff_to_do();
}
};

std::unique_ptr<Calc_Type> createJob(const std::string& name)
{
if (name = "A") {
return std::make_unique<A>();
} else if (name = "B") {
return std::make_unique<B>();
}
return std::make_unique<NoJob>();
}

// somewhere in the code:
auto job = createJob(userInput);
...
job->run();

关于c++ - 模板化唯一指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57096515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com