Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

C++ constexpr is a nasty trap. Because after all it says right on the tin that we're getting a constant expression right? So it's as powerful as Rust's const right?

Nope - of course the usual suspects insisted they needed a way to write non-constant expressions and have that somehow "work" anyway. So whereas a const function in Rust genuinely is constant, a constexpr function in C++ might not be, and we only find out whether it was if we force the compiler to do the operation at compile time. If we leave any gap where it can just delay until runtime that's what happens.

You can literally write a random number generator, label it "constexpr" and a modern C++ compiler goes OK, that's not actually constant, but you didn't technically promise it was constant you just used this useless "constexpr" keyword to gesture performatively at the idea of compile time evaluation without promising anything so we'll only complain if you try to use it in a context where I must know the concrete value at compile time.



True, however I would expect that anyone that knows constexpr is also aware of constinit, consteval and static constexpr.

Does it suck instead of having a single mechanism?

Yes, but the tools are there to actually enforce it at compile time.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: