syntax highlight

Saturday, 3 August 2019

std::is_constant_evaluated: make debugging a little bit harder for yourself!

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.