Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 904
pzelasko Avatar asked Feb 06 '26 18:02

pzelasko


1 Answers

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;
}
like image 81
jotik Avatar answered Feb 09 '26 11:02

jotik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!