编译器无法推断出返回类型? [英] Compiler can't deduce the return type?
问题描述
我正在尝试在自动功能上使用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()
的身体尚未分析.
作为一种补救方法,您可以使用
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屋!