Why are parameters of immediate (consteval
) functions are not considered constant expressions?
consteval void func(int x)
{
int arr[x]; // not valid, x is not a constant expr
...
}
What functionality would have been lost if x
was considered a constant expression? Of course every calls to func
would have to pass a constant expression as an argument, but this is almost certainly the case anyway, since func
is immediate.
If there are some useful cases where an argument to an immediate function can be a non-constant expression, could we require constexpr-ness of a parameter explicitly, as a hypothetical language extension? Would such extension break any existing code or introduce other problems? (It doesn't have to be limited to immediate functions).
consteval void func(constexpr int x)
{
int arr[x]; // valid, x is a constant expression
...
}
func(3); // ok
func(time(nullptr)); // not ok, argument is not a constant expression
Are there any committee papers that explore this design?
I know everything can be done with templates:
template <int x>
consteval void func()
{
int arr[x]; // valid, x is a constant expression
...
}
however templates are syntax-heavy and not very friendly. I would prefer to write myTuple[3]
rather than std::get<3>(myTuple)
. It would be possible if arguments to tuple::operator[]
were constexpr. Since today they are not, such operator[]
cannot be defined.