"using" type alias of class scope: [when] can usages in methods PRECEDE the type alias?
Asked Answered
P

1

5

Yesterday, I was (pleasantly) surprised when I was able to compile code that had a method which used a using type alias even though the declaration of the alias was not until later in the class definition.

  • Is this 'forward' usage of a type-alias valid? (I assume it is, since Clang 5 and GCC 4.9 both work this way.)
  • What rules cover this behavior and the difference between the method body and method signature usages?

Case #1 - using declared after method, valid inside method body (only?)

#include <string>
#include <iostream>

struct X {
  std::string create() {     // fails to compile if Y used in signature
      return Y{"hello!"};    // compiles when Y here
  }

  using Y = std::string;     // declared at bottom
};

int main() 
{
    std::cout << X().create() << std::endl;
}

Case #2 - using declared above is [also] valid in signature

#include <string>
#include <iostream>

struct X {
  using Y = std::string;     // declared at top

  Y create() {               // can use Y here as well
      return Y{"hello!"};
  }
};

int main() 
{
    std::cout << X().create() << std::endl;
}
Partisan answered 10/2, 2020 at 17:33 Comment(1)
I'm sure there is a dupe somewhere, but it's because a function body is a complete-class context.Contumelious
U
8

This has to do with the complete-class context. When you are in the body of a member function, the class is considered complete and can use anything defined in the class, no matter where in the class it is declared.

The return type of a member function is not part of the complete-class context so you can only use names that are known about at that point in the code.

Urinalysis answered 10/2, 2020 at 17:40 Comment(1)
Note: This term was only introduced in C++20, but the same concept applies before that.Biscay

© 2022 - 2024 — McMap. All rights reserved.