Products > Programming

C++ "constexpr" function arguments

(1/3) > >>

So, C++ has constexpr "variables" and "functions."
Does it have an equivalent for function ARGUMENTS?
Ideally, I'd like to have overloaded functions:void foo(constexpr int bar) { ... }

void foo(int bar) { ... }
so that if I call foo() with a compile-time constant as an argument, it would invoke the first code, and if it wasn't, it would invoke the second...
(Yeah, I'm aware that I can do about the same thing using __builtin_constant_p(), at least with gcc.  But that tends to be ugly, and not portable, and it seems like the sort of thing  that would get standardized, eventually.)

Doesn't seem possible at the moment, but there is a proposal in the works:

Here's a discussion on implementing is_constexpr() function for C++2a:

Here's an old SO discussion of the problem:

At that time looks like the best way to discriminate based on a constexpr parameter was to write a macro which called one implementation or another based on the return value of __builtin_constant_p().

Just a thought or question about that...

As I get it, constexpr represents expressions that can be fully evaluated statically (at compile-time).
I guess obviously any litteral, or a combination thereof, is a constexpr. But there are possibly many other, more subtle cases, in which some expression can actually be fully evaluated statically, whereas it's really NOT obvious to the eye of the programmer. In that case, isn't using constexpr potentially very slippery, especially if you're making assumptions on what a constexpr is, and implements functions that act differently for constexpr parameters (something not currently available, and I guess, what I just said was probably part of the discussions?)

Overloaded functions can be so slippery already.

The consensus seems to be that constexpr evaluation is Turing-complete:

In C++11 it wasn't, but apparently it has since been fixed:

Template meta-programming is also Turing-complete so now there are two ways to hang your compiler.


--- Quote from: ledtester on September 26, 2019, 04:00:12 pm ---(...)
Template meta-programming is also Turing-complete so now there are two ways to hang your compiler.

--- End quote ---

Good lord. :-DD

Someday someone will write a full graphics Tetris game intended to run at compile-time inside a C++ compiler.


[0] Message Index

[#] Next page

There was an error while thanking
Go to full version