1

从 C++17 开始,模板函数可以在编译时计算的表达式的函数中返回一种或另一种类型:

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
}

有没有等价的switch?

我没有成功尝试过:

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;
    }
}
4

1 回答 1

1

您可以专门化功能模板:

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

于 2019-11-29T12:11:02.940 回答