Boiethios Boiethios - 16 days ago 5
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)
{
return
std::conditional<
std::is_same<ListT, LicencesList>::value, "licences",
std::conditional<
std::is_same<ListT, BundlesList>::value, "bundles",
std::conditional<
std::is_same<ListT, ProductsList>::value, "products",
std::conditional<
std::is_same<ListT, UsersList>::value, "users",
nullptr
>
>
>
>;
}


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

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