使用字符串选择模板类的专用化

select specialization of template class using a string

本文关键字:专用 字符串 选择      更新时间:2023-10-16

我使用策略创建了几种类型,即

template <typename PolicyA, typename PolicyB>
class BaseType : PolicyA, PolicyB
{};
struct MyPolicyA {};
struct MyPolicyB {};
struct OtherPolicyB {};
using SpecializedTypeX = BaseType<MyPolicyA, MyPolicyB>;
using SpecializedTypeY = BaseType<MyPolicyA, OtherPolicyB>;

现在我想介绍一些机制,它允许我根据命令行等输入优雅地选择应该使用哪个 SpecializedType。理想情况下,它将是一个工厂方法,创建正确类型的对象,例如:

auto CreateSelectedSpecializedType(const std::string &key);
// selected has type SpecializedTypeX
auto selected = CreateSelectedSpecializedType("SpecializedTypeX");  

我将不胜感激任何建议。谢谢!

C++类型不可能依赖于运行时数据,因为类型在编译时是静态固定的。因此,不可能使函数的返回类型依赖于输入参数的值。因此,您可以做的最好的事情可能是为所有策略创建一个公共基类,例如:

struct CommonBase {};
template <typename PolicyA, typename PolicyB>
class BaseType : CommonBase, PolicyA, PolicyB {};
struct MyPolicyA {};
struct MyPolicyB {};
struct OtherPolicyB {};
using SpecializedTypeX = BaseType<MyPolicyA, MyPolicyB>;
using SpecializedTypeY = BaseType<MyPolicyA, OtherPolicyB>;
CommonBase * createObjectOfType(std::string const & type) {
    if (type == "SpecializedTypeX")
        return new SpecializedTypeX();
    if (type == "SpecializedTypeY")
        return new SpecializedTypeY();
    // etc...
    return nullptr;
}