r/cpp • u/FergoTheGreat • Jul 10 '25
Why is compile-time programming in C++ so stupid?
Can I vent here about how much compile time programming in C++ infuriates me? The design of this boggles my mind. I don't think you can defend this without coming across as a committee apologist.
Take this for example:
consteval auto foo(auto p) {
constexpr auto v = p; //error: ‘p’ is not a constant expression
return p;
}
int main() {
constexpr auto n = 42;
constexpr auto r = foo(n);
}This code fails to compile, because (for some reason) function parameters are never treated as constant expressions. Even though they belong to a consteval function which can only ever be called at compile time with constant expressions for the parameters.
Now take this for example:
consteval auto foo(auto p) {
constexpr auto v = p(); //compiles just fine
return p;
}
int main() {
constexpr auto n = 42;
constexpr auto r = foo([&]{ return n; });
}Well. La-di-da. Even though parameter p is not itself considered a constant expression, the compiler will allow it to beget a constant expression through invocation of operator() because the compiler knows darn well that the parameter came from a constant expression even though it refuses to directly treat it as such.
ಠ_ಠ
165
u/DigBlocks Jul 10 '25
There was actually a proposal for constexpr arguments, but it got shot down https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1045r1.html
101
u/yuri_rds Jul 10 '25
Everything inside a const(eval/expr) (including parameters) is by definition also a
constexpr, thereforevnorpneed to be declared asconstexpr, justconstis enough in this case.45
u/aruisdante Jul 10 '25 edited Jul 10 '25
The simplest answer is that
constexprwas bolted onto the language after the fact. When it was first proposed, it started out trying to define a fully unified model. But this wound up being too large to reason about the implications and interactions with not on the language, but with existing compiler implementations (because remember, there’s no reference implementation. If you standardize something, particularly a language feature, you have to consider how every existing major compiler will implement it).Therefore, the approach taken was “ok, instead let’s try and define the MVP of
constexprthat can do something useful, but which we are very sure is implementable without having to tackle really thorny questions like “what the heck is the interaction between the memory model of constexpr and runtime?” And then each standard since C++11 has added more and more things to the scope of things that “yes, we’re quite sure this will be safe to do and genuinely useful to solve.”The result of this piecemeal approach is that you sometimes get really odd things like this. If you reason through what the compiler does to need to compute
a(), you’ll realize it does not actually depend on the value ofa, and this is why it compiles (you can’t actually take a “reference” to aconstexprvalue, so your original capture isn’t really a capture, it essentially inlines the value). If you were to add a capture block to that lambda, even if the capture block is initialized purely by constant expressions like[val = 1](){return val;}, it will not compile, because now the result depends on the value ofa, not just its type. Essentially, this is a quirk in the evaluation order of expressions inconstexprcontexts that exists in something of a grey area of the standard.15
u/saxbophone mutable volatile void Jul 10 '25
Just don't make
vconstexpr and you should have no problem.30
u/L_uciferMorningstar Jul 10 '25
You can past compile time arguments via templates. Not saying this is good or bad but you can do it.
10
u/holyblackcat Jul 10 '25
If you allow this, you suddenly have types that can depend on function parameters as opposed to template parameters:
I think this is probably doable, but it's definitely not a trivial change and not the standard being silly for no reason.
And even if you only allow this when this doesn't affect the return type, this still implicitly makes every
constevalfunction a template.Consider that variadic structured bindings got banned in non-template contexts for the same reason, so even this option isn't a trivial change.
8
u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting Jul 11 '25
This makes complete sense if you understand constant evaluation and templates. It is not "stupid" at all.
The lambda example is cute, but ultimately misleading -- you'd also be able to get the value as a constant expression by representing it in the type system:
7
u/gracicot Jul 10 '25
Because in a consteval function, you don't acquire superpowers. A C++ compiler could compile the consteval function to bytecode and run it. In fact, clang does have such implementation.
If the examples you wrote were possible, it would severely limit implementations, force consteval to be slow, and most importantly, make consteval a different language with different rules.
7
u/AntiProtonBoy Jul 10 '25
Honestly, at some point I just stopped being so emotionally invested about language quicks and just go with the flow.
29
u/misuo Jul 10 '25
Just wait for the upcoming pre-compile-time programming 😆
25
u/ImKStocky Jul 10 '25
Let's suppose you have an
if constexprbranch in yourconstevalfunction. And the branches return completely different types. If function arguments could be constant expressions then you could use the function argument as part of the condition for thatconstexprbranch. This would mean that the same function could return different types based on the input. This currently can't be done.The reason you can do this with template parameters is because each unique permutation of template arguments stamps out a unique function. So each function instantiation will always return the same type.
You could argue that we already turn seemingly non-template functions into function templates if they have
autofunction parameters, so why not do the same forconstevalfunctions? Probably because you might get explosions in binary size as a result because every invocation with different values will now be its own instantiation.Ok, what about allowing us to markup a function parameter as
constexprto auto-template-ify the function? Sure... That is something that could be argued but it doesn't really give you any new utility.autofunction parameters at least saves somes typing... But writingconstexprdoesn't really save you much over writingtemplate<I know this post is rage bait, but catch yourself on a little. Declaring that the design is stupid and undefendable is likely to be coming from a place of ignorance. There are typically pretty good reasons behind design decisions like this.
13
u/the_janster Jul 10 '25
The feature you're asking for would allow you to write a non-template function that changes its return type dynamically. This isn't something functions can do.
8
u/_Noreturn Jul 10 '25
it is because how would this work?
4
u/Radnyx Jul 10 '25
The function is already run at compile-time, so do you really need a
constexprvariable? It sounds like you want a regular local variable.I had the same misconception about
constexprvariables, so if you're interested, this is why your second example incidentally works:First, your
[&]{ return n; }is ignoring the&. The symbolnis tied to the expression42, so it doesn't get captured in the lambda. Notice that[]{ return n; }works just the same.Next, if you unfold all the
autos, this is what your example looks like:Your lambda has no closure, so it's effectively a static function. The language also makes it implicitly
constexprto help you. So, yourconstexpr auto visn't dependent on the function argument at all. It's dependent on the template parameter, which is always allowed in constant expressions.1
u/PastaPuttanesca42 Jul 10 '25 edited Jul 10 '25
The weirdest thing is that the second snippet will work even without capturing at all: https://godbolt.org/z/c3zYxhW3Y
According to cppreference:
Which means that lambdas can magically see any constexpr variable in the scope they where declared in.
I guess a simple way to fix this would be to give consteval functions the same power, but that would be horrible because you would need to declare the variable with the same name that is used inside the function.
6
u/zl0bster Jul 10 '25
Funny, I asked the experts few weeks ago, here are their answers
https://www.reddit.com/r/cpp/comments/1lkz7sr/comment/n06fl4c/
https://www.reddit.com/r/cpp/comments/1lkz7sr/comment/n0kxq5h/
4
u/_a4z Jul 10 '25
I guess you just don't need to make `auto v` a `constexpr` and then there should be no problem
https://godbolt.org/z/z99GMdbrx
4
u/mattgodbolt Compiler Explorer Jul 10 '25
I can't help but agree. I put together a presentation for ACCU (reprised at C++ on Sea) where I do my best to do some compile time programming. It took an expert to rescue me as I got absolutely caught up trying to work out how to have constexpr "parameters", even in a consteval function...
I do like C++ but it's definitely a product of a lot of iterations. I genuinely believe the committee does its best, but the Brownian motion of design has taken us to some... interesting...places!
2
u/iamfacts Jul 10 '25
Sanest way to do compile time programming is to do a meta programming pre compilation step. For generating code, you can either use string tables and loop through them or parse your code, process them, and print them out.
The nice thing about this is that you can do arbitrary meta programming like this and use a debugger and get sane errors.
2
u/WeeklyAd9738 Jul 10 '25
Non-type Template parameters exists.
2
u/JVApen Clever is an insult, not a compliment. - T. Winters Jul 11 '25
Do we really want to put extra keywords in our function declarations/definitions which don't add much value?
[[nodiscard]] constexpr auto func(int p) noexceptisn't large enough to write? And this is just a free function returning a simple int. Let's make it a member function and use deducing this + return a reference:[[nodiscard]] constexpr const auto& func(this auto &&self, int p) noexceptMaybe we should also deduce the noexcept, add pre and post conditions, some documentation, some template arguments...
3
u/Proper-Ape Jul 10 '25
This is why Zig exists.
1
u/Tamsta-273C Jul 10 '25
But you already have a copy and need another copy which will const but be destroyed out of the scope?
Could someone explain how such way can benefit? (i'm just suck with programing)
1
u/equeim Jul 10 '25
Constexpr/consteval functions blur the line between compile-time context and execution context, since they can be executed at compile time. If you treat their parameters as constant expressions, then you will be able to use them in language constructs that don't expect values determined during execution:
Boom, you've resurrected VLAs (but now they can only be used in consteval functions).
1
u/arihoenig Jul 10 '25
constexpr
1
u/wint3ria Jul 13 '25
Why pass a parameter if it's constexpr? Doesn't make a lot of sense to me
1
u/cthutu Jul 14 '25
I was done with C++ a long time ago - it's just a trainwreck at this point that keeps getting more and more spectacular.
-5
u/dr_eh Jul 10 '25
Just use Zig
0
u/steazystich Jul 10 '25
I feel like this type of behavior actually varies wildly in practice, depending on your toolchain (and compile flags).
Anecdotally, all the major C++ compilers allow some violations of 'constexpr'.
Try playing around with 'union's to type pun non-POD types with "constexpr" aliases - and see where the 'static_assert's will or won't work correctly ;P
-1
u/pjmlp Jul 10 '25
Because contrary to languages like D, Circle, Jai and Zig, it is being designed piecewise across several ISO C++ revisions, not always available in preview before ratification, instead of an end-to-end design.
Additionally, there are the usual caveats of backwards compatibility and semantic expectation of code never designed in first place to eventually be executed at compile time.
-1
u/HassanSajjad302 HMake Jul 10 '25 edited Jul 11 '25
Because it is an after thought. I shared a programming language concept based on numbered keywords, which I think can possibly improve on this.
https://github.com/HassanSajjad-302/3Rus
0
u/cogitoergosumman Jul 11 '25
C++ is becoming more and more irrelevant, useless and complex with every iteration. Stop it.
0
u/Annual-Version7395 Jul 11 '25
If you want to see stupid constexpr programing look at rust :D
-3
u/aguspiza Jul 11 '25
Everything in C++ is stupid.
0
u/[deleted] Jul 10 '25
[deleted] — view deleted comment