3

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

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

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

4

1 回答 1

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;
}
于 2016-03-07T14:30:50.067 回答