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;
}
You can write a trait
and specialize it accordingly:
then use it:
Alternatively you could write a function that utilizes a series of
constexpr ifto return the right string for given type. Though, I wouldn't expect this to be cleaner or more readable.