To avoid recursive template programming I am relying on the short circuit evaluation of the result of lambdas combined with logical && using a fold expression. Is that safe to do or will the compiler optimize away the expression because it is not used even if it has side effects?
For example consider the following code:
#include <cassert>
#include <utility>
template <typename... Ts>
int count_leading_good(Ts &&...ts) {
int N{0};
([&](auto &&t) -> bool {
if (t.good) {
N += 1;
return true;
}
return false;
}(std::forward<Ts>(ts)) && ...);
return N;
}
struct A {
bool good{true};
};
struct B {
bool good{false};
};
int main(int argc, char *argv[]) {
assert(count_leading_good(A{}, A{}, A{}, B{}, A{}) == 3);
}
Is it guaranteed that the assert never fails, i.e. that the fold expression will never be optimized away for any compilation flags?
Is there some C++ rule that ensures this?
Note that the result of the logical && is not used.
language-lawyertag because this seems like a fit to have an answer quote the standard.Nchanges), so you are only relying on the fact that&&will short circuit and that has been asked and answered on SO before.