If there's a constexpr if statement, why not other constexpr statements too?

Viewed 1547

Is there any reason only if constexpr to be included in C++17?

I could do this:

template <int N>
constexpr int fib() {
    if constexpr (N == 1 || N == 2) {
        return 1;
    } else {
        return fib<N - 1>() + fib<N - 2>();
    }
}

Why haven't the C++ committee considered switch constexpr too?

template <int N>
constexpr int fib() {
    switch constexpr (N) {
        case 1:
        case 2: return 1;
        default: return fib<N - 1>() + fib<N - 2>();
    }
}

It looked much cooler with switch constexpr

Or even a premature compile-time loop unwind with for constexpr/while constexpr without the use of template substitution/recursive template function:

constexpr void printFoo() {
    for constexpr (auto i = 0; i < 10; i++) {
        cout << fib<i>() << endl;
    }
}

Will they be included in C++20/future versions of C++?

3 Answers
Related