Search code examples
c++boostc++14metaprogrammingtemplate-meta-programming

How to assign static constexpr field value based on template type


I'd like to assign static constexpr field of a class based on template type. I've found out below solution but I guess it is not best solution especially if there are other types to support. Maybe some kind of constexpr map? (I can use STL and/or boost)

#include <iostream>
#include <string_view>

template <typename T>
struct Example
{
    static constexpr std::string_view s{std::is_same_v<T, int> ? "int" 
         : (std::is_same_v<T, double> ? "double" : "other")};
};


int main()
{
    const Example<int> example;
    std::cout << example.s << std::endl;
    return 0;
}


Solution

  • You can write a trait

    template <typename T> 
    struct st { };
    

    and specialize it accordingly:

    template <> struct st<int> { static constexpr std::string_view value{"int"}; }
    // ... other types
    

    then use it:

    template <typename T>
    struct Example
    {
        static constexpr std::string_view s = st<T>::value;
    };
    

    Alternatively you could write a function that utilizes a series of constexpr if to return the right string for given type. Though, I wouldn't expect this to be cleaner or more readable.