C++如何实现多字符串参数工厂方法创建模板类并减少if分支
优化方案:使用查表法消除分支
核心思路是预先把所有字符串组合和对应的构造逻辑存到映射表中,工厂函数运行时直接查表返回对应实例,完全消除if分支。
实现代码
#include <unordered_map> #include <string> #include <functional> #include <memory> // 你的已有类型定义 class Base {}; template <typename T, typename O> class Derived : public Base {}; struct LLT {}; struct LU {}; struct AMD {}; struct COLAMD {}; // 定义构造函数的统一类型 using Creator = std::function<std::unique_ptr<Base>()>; // 全局注册表,用函数内静态变量避免初始化顺序问题 const auto& get_creator_table() { static const std::unordered_map<std::string, Creator> table = { {"LLT|AMD", []() { return std::make_unique<Derived<LLT, AMD>>(); }}, {"LLT|COLAMD", []() { return std::make_unique<Derived<LLT, COLAMD>>(); }}, {"LU|AMD", []() { return std::make_unique<Derived<LU, AMD>>(); }}, {"LU|COLAMD", []() { return std::make_unique<Derived<LU, COLAMD>>(); }} }; return table; } std::unique_ptr<Base> create_A(const std::string& type, const std::string& order) { auto key = type + "|" + order; const auto& table = get_creator_table(); auto iter = table.find(key); if (iter != table.end()) { return iter->second(); } // 非法参数可根据业务需要返回空指针、抛异常或返回默认实例 return nullptr; }
可选优化:避免字符串拼接
如果不想拼接字符串,可改用std::pair作为key搭配std::map实现:
const auto& get_creator_table() { static const std::map<std::pair<std::string, std::string>, Creator> table = { {{"LLT", "AMD"}, []() { return std::make_unique<Derived<LLT, AMD>>(); }}, {{"LLT", "COLAMD"}, []() { return std::make_unique<Derived<LLT, COLAMD>>(); }}, {{"LU", "AMD"}, []() { return std::make_unique<Derived<LU, AMD>>(); }}, {{"LU", "COLAMD"}, []() { return std::make_unique<Derived<LU, COLAMD>>(); }} }; return table; } std::unique_ptr<Base> create_A(const std::string& type, const std::string& order) { const auto& table = get_creator_table(); auto iter = table.find({type, order}); return iter != table.end() ? iter->second() : nullptr; }
方案优势
- 完全消除if-else分支,运行时性能稳定,不会随支持的组合数量增加出现分支预测损耗
- 后续新增类型或排序策略时,只需在注册表中新增一行配置即可,无需修改工厂函数主逻辑,符合开闭原则
- 所有支持的组合统一维护,代码可读性和可维护性更高
内容的提问来源于stack exchange,提问作者Rick Vencent
相关产品推荐
相关产品推荐

