Let's say I want to access a member variable a only if it exists. I tried below
template <typename T> concept hasA = requires(T t) { { t.a }; }; void foo(){ struct X { int b; // X does not have a }; X x; if constexpr (hasA<X>) { x.a = 1234; // This line should not be compiled but ... } } But I got a compilation error:
<source>:13:7: error: no member named 'a' in 'X' x.a = 1234; ~ ^ (See https://godbolt.org/z/xGzo7axv8)
I expected hasA<X> must have been false in compilation time and therefore the if-constexpr should have not be evaluated at all.
if constexprworks. You must be in a template to have branches dropped, and even then only if they are dependent on a template parameter.