2

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;
    }
}
mfnx
  • 2,894
  • 1
  • 12
  • 28
  • 2
    I don't think there is a constexpr switch, you may need to rewrite it as a constexpr if else if chain. – tkausl Nov 29 '19 at 11:17
  • 1
    No, at the moment (C++17) – max66 Nov 29 '19 at 11:21
  • 2
    "Since C++17, we can return one type or another in function" not strictly true. You can have a function template which instantiates to functions returning different types based on it's template parameters. – Caleth Nov 29 '19 at 11:30
  • @Caleth edit -> "a template function can return" which should be ok. Thx. – mfnx Nov 29 '19 at 11:35
  • Since a `constexpr` `if`/`else` chain is evaluated at compile time, there's no runtime performance penalty for writing `if`/`else` compared to `switch` in this case (there is a readability penalty, which is unfortunate). – Toby Speight Nov 29 '19 at 11:52

1 Answers1

1

You could specialize the function template:

template <size_t N>
constexpr auto f()
{
    // default case
    return -1;
}
template<> 
constexpr auto f<1>()
{
    return 1.2;
}
template<>
constexpr auto f<2>()
{
    return std::array<double,25>();
}

https://godbolt.org/z/dF_BSW

Anthony Williams
  • 66,628
  • 14
  • 133
  • 155