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.

  • 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. – StoryTeller - Unslander Monica Mar 28 '23 at 09: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. – freakish Mar 28 '23 at 09:10

0 Answers0