3 ms·
I think it's only consistent. Static assertions should always always always hold (things like type checks etc), if you really want to only evaluate it in that b
by lorenzhs 10y ago
I think it's only consistent. Static assertions should always always always hold (things like type checks etc), if you really want to only evaluate it in that branch you can still do
if constexpr (foo) {
static_assert(!foo || /* assertion */);
} else {
static_assert(foo || /* assertion */);
}
(this gets ugly fast with lots of else-ifs, but it's a workaround - I don't know why you'd ever need it, though)
- toth 10y agoHmm, it seems this constexpr if is much more limited than I realized then. If I understood correctly the code in the the body of the constexpr if has to be correct even if the condition does not hold. I.e., this code: template<typename T> void func(T x) { if constexpr ( std::is_same< T, ClassWithMemberF>::value ) { x.f(); } } will not work if you pass in a type for x that does not have a member function f. Is my understanding right? If so, constexpr if is not nearly as nice as I thought...
- RcouF1uZ4gsC 10y agoIn my reading of it, this code would work. The code in if constexpr must be well-formed but does not have to be semantically valid. Your code is well-formed but not semantically valid, so this would be the perfect use for if constexpr
- toth 10y agoYou may be correct, and I certainly hope you are. But if that's the case then the static_assert behavior seems all the more puzzling. In particular if this code works, then you can roll your own "static_assert" that will not trigger from the not taken branches.