c++ - 抽象工厂改进

标签 c++

已编辑:我决定为 future 的读者编辑这篇文章。简而言之,它显示了一种可接受的方式来调用模板列表中模板类型的构造函数。例如,以下内容:

int main()
{
    unique_ptr<factory> real_widget_factory(new widget_factory(5.0, 6.0));
}

不仅限于:

    unique_ptr<factory> real_widget_factory(new widget_factory()); // empty

最佳答案

该标准提供了您需要的所有必要基础设施。您可以删除所有这些代码。

template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) {
    return std::unique_ptr<T>(std::forward<Args>(args)...);
}
struct train_factory {
    train_factory(std::function<std::unique_ptr<locomotive>()> ml,
        std::function<std::unique_ptr<freight_car>()> mc)
        : make_locomotive(std::move(ml)),
        , make_car(std::move(mc)) {}
    std::function<std::unique_ptr<locomotive>()> make_locomotive;
    std::function<std::unique_ptr<freight_car>()> make_car;
};
train_factory make_concrete_factory(double x1, double x2) {
    return train_factory(
        [=] { return make_unique<real_locomotive>(x1); },
        [=] { return make_unique<real_car>(x2); }
    );
}
int main() {        
    auto fact = make_concrete_factory(1.0);
    auto loc = fact.make_locomotive();
}

这似乎可以满足您的所有要求。在这种情况下,函数具有绑定(bind)到工厂的参数(并且此绑定(bind)是任意的)。当然,您也可以根据需要修改函数以获取参数,或者以任意方式和组合使用两者。

struct train_factory {
    std::function<std::unique_ptr<locomotive>(double)> make_locomotive;
    std::function<std::unique_ptr<freight_car>(double)> make_car;
};
train_factory make_concrete_factory() {
    return train_factory {
        [](double x1) { return make_unique<real_locomotive>(x1); },
        [](double x2) { return make_unique<real_car>(x2); }
    };
}
int main() {        
    auto fact = make_concrete_factory();
    auto loc = fact.make_locomotive(1.0);
}

关于c++ - 抽象工厂改进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29721717/

相关文章:

c# - 在 C# 控制台应用程序中运行 C++ 控制台应用程序

c++ - 常量变量与常量引用

c++ - 将十六进制数写入文件

C++ 线程安全和时间效率 : why does thread with mutex check sometimes works faster than without it?

c++ - 上传输入时出现 SIGSEGV 错误

c++ - 在构造函数中使用临时参数作为默认参数

c++ - 在编译时对算术 `std::array` 的 `value_type` 进行零初始化会导致缺少构造函数注释

c++ - 来自 iostream 或内存缓冲区的 Apache Arrow 表

c++ - 如何从 libcurl 获取 URL 的片段部分?

c++ - 当显示为独立对话框时,CPropertyPage 派生对话框不会在 Esc 上关闭