What C++ mechanism should I use instead, to ensure failure only when the condition of an if statement evaluates to false?
According to cppreference
Outside a template, a discarded statement is fully checked. if constexpr is not a substitute for the #if preprocessing directive:
so I suppose you can make your foo() function a template one
template <int = 0>
void foo() {
if constexpr(a == 1) { }
else { static_assert(b != 1, "Fail"); }
}
--- EDIT ---
The OP asks
it's quite problematic to change the function definition just for an assertion somewhere... can't I use some kind of templated gadget instead?
I don't see a way through a type trait.
But if you can use at least C++20, so template lambdas, you can wrap your code inside a template lambda defined inside the foo() function. And call the lambda.
I mean something as follows
enum { a = 1, b = 2 - a};
void foo() {
auto l = []<int = 0>{
if constexpr (a == 1) {
}
else {
static_assert(b != 1, "fail :-(");
}
};
l();
}
int main ()
{
foo();
}
static_assert(a == 1 || b != 1, "fail :-(");Since a static_assert isn't scoped in this case (... because it is static and not in a template), so doesn't matter that it is in the else block.aas I write the static asseration, or whatever alternative I use. Also, DRY.if constexprhas no meaning outside a template. It's purpose is to eliminate the branching when the template is instantiated (hence the need to have aconstexprcondition). In your case, it's equivalent to a regularifbut restricted toconstexprconditions only (which is then useless).