Search code examples
c++templatespolicystatic-polymorphism

select specialization of template class using a string


I have several types created using policies, i.e.

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

Now I would like to introduce some mechanism which allows me to elegantly select which SpecializedType should be used basing on input from e.g. command line. Ideally, it would be a factory method creating object of the proper type, like:

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

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

I'd appreciate any advice. Thanks!


Solution

  • It is impossible to have a C++ type depend on runtime data, because types are fixed statically at compile-time. Hence, it is impossible to make a return type of a function dependant on the values of the input arguments. So probably the best thing you can do is create a common base class for all the policies, e.g:

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