Home > Net >  factory creating different types according to enum values c
factory creating different types according to enum values c

Time:06-10

I have some auto generated structs each logically related to a enum value. can I create a factory using a template function? everything can be resolved at compiled time. I tried something like this:

struct Type1
{
};    

struct Type2
{
};

enum class type_t
{
    first,
    second
};

template <type_t typet>
auto Get_()
{    
    static_assert(typet == type_t::second);
    return Type2();
}  

template <type_t typet>
auto Get_()
{
    static_assert(typet == type_t::first);
    return Type1();
} 
   
template <type_t typet>
auto Get_()
{
    static_assert(false, "no overload");
}    

int main()
{
    auto relatedType1 = Get_<type_t::first>();
    auto relatedType2 = Get_<type_t::second>();
}

CodePudding user response:

In C 11 (and above), you may use an auxiliary traits struct like the following:

template <type_t T>
struct type_selector;

template <>
struct type_selector<type_t::first> {
    using type = Type1;
};

template <>
struct type_selector<type_t::second> {
    using type = Type2;
};

// implement other specializations, if needed

Then, your Get_ function template is simply:

template <type_t typet>
auto Get_() -> typename type_selector<typet>::type {
    return {};
}
  • Related