C++ Logo

std-proposals

Advanced search

[std-proposals] constexpr specifier for function parameters

From: David Brown <david.brown_at_[hidden]>
Date: Thu, 26 Nov 2026 10:58:24 +0100
In C++26, we now have std::constant_wrapper<> and std::cw<> which can
let you pass constant expressions as normal function parameters, and let
them be used as constant expressions within the function definition.
(We are talking about templated functions here, since each
std::constant_wrapper<> instance has a unique type for the value it wraps.)

 From cppreference, we have the example :

 auto make_filled(auto size, int value)
 {
     std::array<int, size> a;
     a.fill(value);
     return a;
 }

This can be called from other code as :

 auto a = make_filled(std::cw<3>, x);

Then "a" is a std::array<3, int> filled with the value of "x".

Prior to C++26, you would write this as :

 template<size_t size>
 auto make_filled(int value)
 {
     std::array<int, size> a;
     a.fill(value);
     return a;
 }

 auto a = make_filled<3>(x);


The use of std::constant_wrapper<> can make the code a little neater and
more consistent - the call site only uses function arguments and does
not also need template arguments, and these can be given in the function
definition in whatever order makes sense.

But it means that every call needs to have "std::cw<>" wrappers
explicitly added - that is more code at each call, more to add, more to
get right, more to understand.


My suggested alternative syntax here would be :

 auto make_filled(constexpr size_t size, int value)
 {
     std::array<int, size> a;
     a.fill(value);
     return a;
 }

 auto a = make_filled(3, x);


Function parameters with the "constexpr" specifier would effectively be
non-type template parameters. This would be another kind of abbreviated
template, in the same sense as the use of concepts or "auto" in place of
types for function parameters. A "constepxr" parameter could be of
fixed type, "auto", a concept, etc., just like any other parameter.

The advantage of this would be to give neater and more "universal"
calling code for template functions with non-type template parameters.
The disadvantage is that it hides the fact that the "size" parameter in
this example must be a constant expression, not a runtime value.


Any thoughts here? Is it an idea that appeals to people, or would it
feel like it is hiding important information? Or am I missing something
crucial that would make this impossible or impractical?

David

Received on 2026-11-26 09:58:35