Currently I am doing:
if constexpr(constexpr_bool_var1) {
auto arg1 = costly_arg1(); auto arg2 = costly_arg2();
if (costly_runtime_function(arg1, arg2)) {
// do X, possibly more constexpr conditions
// do Y
// ...
}
} else {
// do X, possibly more constexpr conditions
// do Y
// ...
}
One possible way is to convert the do X/Y etc. to one function doXY() and call it in both places, however it seems very unwieldy, as I have to write a function that solely exists for convenience of meta programming.
What I want is something like:
if not constexpr(constexpr_bool_var1 && some_magic(costly_runtime_function(arg1, arg2)) {
// do X, do Y
}
Another way is:
auto arg1 = costly_arg1(); // Unneeded extra work out not within constexpr
auto arg2 = costly_arg2();
if (constexpr_bool_var1 && costly_runtime_function(arg1, arg2)) {
} else {
// do X, possibly more constexpr conditions
// do Y
// ...
}
However here arg1 and arg2 are being declared outside the if condition so they will be needlessly instantiated.
if?auto doXY = [] { doX(); doY(); };and then call it in both places.if constexprrequires the test to be done at compile time, and the result ofcostly_runtime_function()will be unknown until run time, it can't be used inif constexpr.constexpr_bool_var1is false, and maybe if it's true but you won't know until runtime? In that case, can't you just dobool do_x_y = true; if constexpr (constexpr_bool_var1) { do_x_y = costly_runtime_function(/* ... */); } if (do_x_y) { /* ... */ }?if (constexpr_val && runtime_val)is optimized intoif (runtime_val)anyway.if constexpris mostly meant to be used when suppressed branch cannot be compiled.