编译器不能推导出返回类型? [英] Compiler can't deduce the return type?

查看:27
本文介绍了编译器不能推导出返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在自动函数上使用 decltype 关键字:

I am trying to use the decltype keyword on an auto function:

struct Thing {
   static auto foo() {
     return 12;
   }
   using type_t =
       decltype(foo());
};

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

And I get the following error (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'

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

Why has the compiler not yet deduced the return type?

推荐答案

因为对于类定义,编译器会首先确定所有的成员名称和类型.函数体在之后被分析.

Because for class definition, compiler will first determine all member names and types. Function body is analyzed after this is done.

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

That's why a class member function can call another member function declared after its own definition.

此时编译正在确定

using type_t = decltype(foo());

函数foo()的主体尚未被分析.

function foo()'s body has not yet been analyzed.

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

As a remedy, you can use

static auto foo() -> decltype(12) {
  return 12;
}

注意:

此现象仅针对类.类外的以下代码将编译:

This phenomenon is only for class. The following code outside a class will compile:

auto bar() { return 12; }

using t = decltype(bar());

这篇关于编译器不能推导出返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆