Why can't fold expressions appear in a constant expression?

Viewed 2250

Consider the following code:

template<int value>
constexpr int foo = value;

template<typename... Ts>
constexpr int sum(Ts... args) {
    return foo<(args + ...)>;
}

int main() {
    static_assert(sum(10, 1) == 11);
}

clang 4.0.1 gives me the following error:

main.cpp:6:17: error: non-type template argument is not a constant expression
    return foo<(args + ...)>;
                ^~~~

This surprised me. Every argument is known at compile time, sum is marked as constexpr, so I see no reason why the fold expression can't be evaluated at compile time.

Naturally, this also fails with the same error message:

constexpr int result = (args + ...); // in sum

[expr.prim.fold] isn't very helpful, it's very short and only describes the syntax allowed.

Trying out newer versions of clang also gives the same result, as does gcc.

Are they actually allowed or not?

3 Answers
Related