Since C++17, a template function can return one type or another in function of an expression evaluated at compile-time:
template <size_t N>
constexpr auto f()
{
if constexpr (N == 1)
return 1.0; // return an double
else if constexpr (N == 2)
return std::array<double,N>(); // return an array of doubles
else
return -1; // return an int
}
Is there any equivalent for switch?
I've unsuccessfully tried:
template <size_t N>
constexpr auto f()
{
switch (N) // also switch constexpr (N) -> syntax error
{
case 1: return 1.0;
case 2: return std::array<double,N>();
default: return -1;
}
}