Boiethios Boiethios - 1 year ago 111
C++ Question

Want kind of constexpr switch case on type

I am currently doing this trick to have a cstring based on a type:

template<class ListT> static char constexpr * GetNameOfList(void)
std::is_same<ListT, LicencesList>::value, "licences",
std::is_same<ListT, BundlesList>::value, "bundles",
std::is_same<ListT, ProductsList>::value, "products",
std::is_same<ListT, UsersList>::value, "users",

But this code is not very good-looking, and if we want to check more types, this could be unreadable. Is it a way to do the same thing as if there were a switch case block?

Actually, the code is more complicated than that, because std::conditional need some type, so we need some class to do the trick:

struct LicenceName { static char constexpr * value = "licences"; };

for example.

Answer Source

You don't need to resort to metaprogramming, plain ifs work just fine:

template<class ListT>
constexpr char const *GetNameOfList() {

    if(std::is_same<ListT, A>::value) return "A";
    if(std::is_same<ListT, B>::value) return "B";
    if(std::is_same<ListT, C>::value) return "C";
    if(std::is_same<ListT, D>::value) return "D";

    return nullptr;

See it live on Coliru

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download