编译器无法推断出返回类型?

Dar*_*bik 11 c++ decltype auto c++14

我试图decltype在自动功能上使用关键字:

struct Thing {
   static auto foo() {
     return 12;
   }
   using type_t =
       decltype(foo());
};
Run Code Online (Sandbox Code Playgroud)

我得到以下错误(gcc 7.4):

<source>:6:25: error: use of 'static auto Thing::foo()' before deduction of 'auto'
            decltype(foo());
                         ^
<source>:6:25: error: use of 'static auto Thing::foo()' before deduction of 'auto'
Run Code Online (Sandbox Code Playgroud)

为什么编译器还没有推断出返回类型?

lll*_*lll 13

因为对于类定义,编译器将首先确定所有成员名称和类型.完成分析功能体.

这就是为什么类成员函数可以调用在其自己的定义之后声明的另一个成员函数.

在编译点确定

using type_t = decltype(foo());
Run Code Online (Sandbox Code Playgroud)

功能foo()的身体尚未分析.

作为补救措施,您可以使用

static auto foo() -> decltype(12) {
  return 12;
}
Run Code Online (Sandbox Code Playgroud)

注意:

这种现象仅适用于上课.类外的以下代码将编译:

auto bar() { return 12; }

using t = decltype(bar());
Run Code Online (Sandbox Code Playgroud)