select 使用字符串对模板 class 进行特化

select specialization of template class using a string

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

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>;

现在我想介绍一些机制,让我可以优雅地 select 根据来自的输入,应该使用哪个 SpecializedType。命令行。理想情况下,它将是一个创建适当类型对象的工厂方法,例如:

auto CreateSelectedSpecializedType(const std::string &key);

// selected has type SpecializedTypeX
auto selected = CreateSelectedSpecializedType("SpecializedTypeX");  

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

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

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;
}