【问题标题】:"using" type alias of class scope: [when] can usages in methods PRECEDE the type alias?类范围的“使用”类型别名:[何时]方法中的用法可以在类型别名之前使用吗?
【发布时间】:2020-05-26 01:44:59
【问题描述】:

昨天,当我能够编译具有使用 using type alias 的方法的代码时,我(令人愉快地)感到惊讶,尽管别名的声明直到类定义的后面才声明。

  • 这种类型别名的“前向”用法是否有效? (我认为是这样,因为 Clang 5 和 GCC 4.9 都以这种方式工作。)
  • 哪些规则涵盖此行为以及方法主体和方法签名用法之间的区别?

案例#1 - 使用声明后的方法,在方法体内有效(仅?)

#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;
}

案例 #2 - 使用上面声明的 [也] 在签名中有效

#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;
}

【问题讨论】:

标签: c++ language-lawyer type-alias


【解决方案1】:

这与complete-class context 有关。当您在成员函数的主体中时,该类被认为是完整的,并且可以使用该类中定义的任何内容,无论它在类中的哪个位置声明。

成员函数的返回类型不是完整类上下文的一部分,因此您只能使用代码中当时已知的名称。

【讨论】:

  • 注意:该术语仅在 C++20 中引入,但之前的概念相同。
猜你喜欢
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 2020-07-25
相关资源
最近更新 更多