我正在尝试构建一个依赖于输入参数的类型的对象.例如,我的对象被称为'进程',并且在运行时输入2到5(包括)之间的整数,并且会发生类似这样的事情:
if (input == 2) TwoJ process;
if (input == 3) ThreeJ process;
if (input == 4) FourJ process;
if (input == 5) FiveJ process;
Run Code Online (Sandbox Code Playgroud)
显然上述方法不起作用,因为该对象立即超出范围.有没有办法很好地实现这个?干杯
使用工厂函数返回指向基Process类的智能指针,其实现由提供给工厂函数的整数值确定(要求所有类都具有公共基数).
例如:
class Base_process
{
public:
virtual ~Base_process() {}
virtual void do_something() = 0;
};
class TwoJ : public Base_process
{
public:
void do_something() {}
}
class ThreeJ : public Base_process
{
public:
void do_something() {}
}
std::unique_ptr<Base_process> make_process(int a_type)
{
if (a_type == 1) return std::unique_ptr<Base_process>(new TwoJ());
if (a_type == 2) return std::unique_ptr<Base_process>(new ThreeJ());
// Report invalid type or return an acceptable default if one exists.
throw std::invalid_argument("Unknown type:" + std::to_string(a_type));
}
Run Code Online (Sandbox Code Playgroud)