Search code examples
c++templatesconstexprauto

Why there are no constexpr params for a function in C++?


Would be handy and nice to write something like this:

void f(double a, int constexpr b, bool c) {}

i.e. to mix non-constexpr and constexpr params inside a regular (runtime, non constexpr) function. Also call of such function would be clean and simple as f(a, 123, b) without difficult to read template params.

Of cause function above should behave (and implemented in compiler underneath) as if it was just a regular templated function (with different order of params):

template <int b>
void f(double a, bool c) {}

And this template variant above can be used instead of first variant, but first variant is still very nice as a syntax sugar of the second variant.

For example latest C++ already has a nice syntax sugar for having both params and return value as auto (same like in lambdas):

auto f(int x, auto y) { return y; }

Sure one may ask why not to have all params as runtime params, like in function below, anyway compilers often inline everything:

void f(double a, int b, bool c) {}

But this runtime-passing of all params not always guarantees inlining and/or other compile-time-constant optimizations. Also it doesn't allow to use variable b within constexpr context for example inside if constexpr().

My question is why C++ still has no such feature as mix of constexpr and non-constexpr params among function's params? Also maybe there are proposals or future plans for that?


Solution

  • There seems to be some standardization effort, but I would say duplicate functionality is hardly useful. Just pass the constexpr arguments as template arguments. How would your version interact with function pointers? Are you also proposing int constexpr should be a distinct type? Or are you proposing it should be nicer-syntax for the templated version? Should this compile:

    void foo(int constexpr);
    
    void (*fp)(int) = foo;
    

    If you can nicely fit this idea into the C++ type system, and you feel the gain is worth the standardization effort, have a look at How To Submit a Proposal.