1

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.

2
  • 6
    The trait is false. But that's not how if constexpr works. You must be in a template to have branches dropped, and even then only if they are dependent on a template parameter. Commented Mar 28, 2023 at 9:08
  • 1
    Unfortunately C++ will still parse and check the branch, even if "if constexpr" condition is false. It is quite different from how "requires" works. Commented Mar 28, 2023 at 9:10

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.