Posts for 2019 August
std::is_constant_evaluated: make debugging a little bit harder for yourself!
Post by Nico Brailovsky @ 2019-08-03 | Permalink | 2 comments | Leave a comment
Let's pretend you find this:
const int a = foo();
int b = foo();
Would you be tempted to assume that a==b, always? I would. What if 'foo' actually depends on a global variable, and its return value depends on that global setting? Suddenly the code above will raise a few eyebrows in a code review session.
Coming to your friendly c++20 standard now:
constexpr int foo() {
return (std::is_constant_evaluated())? 42 : 24;
}
bool a() {
const int x = foo();
return x == foo();
}
I'm sure with careful usage, is_constant_evaluated will allow library writers to create much more performant code. I'm also sure I'll lose a lot of hair trying to figure out why my debug code (cout << foo()
, anyone?) prints different values than my production
code.