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

时间:2016-03-07 14:15:46

标签: c++ templates policy static-polymorphism

我有几种使用政策创建的类型,即

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

我很感激任何建议。谢谢!

1 个答案:

答案 0 :(得分:2)

不可能让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;
}