为什么尚未定义具有推导的返回类型的内联方法? [英] Why this inline method with deduced return type not defined yet?
问题描述
#include <string>
#include <type_traits>
class C
{
static auto func() { return std::string("hello"); }
static_assert(std::is_same<decltype(func()), std::string>::value, "");
};
GCC和Clang都不接受,表示在定义func
之前已使用它.为什么?
Neither GCC nor Clang accept this, saying that func
is used before it is defined. Why?
将推导的auto
返回类型更改为std::string
使其起作用.
Changing the deduced auto
return type to std::string
makes it work.
推荐答案
decltype
构造产生声明的标识符或表达式的类型.当func
用返回类型声明时,则调用表达式func()
的类型是已知的,并且一切都会按预期进行.
The decltype
construction produces the declared type of an identifier or expression. When func
is declared with a return type, then the type of the call expression func()
is known and everything works as expected.
但是,当使用返回类型占位符auto
声明func
时,func
的声明取决于其定义,因此func
的类型也因此而定.在定义函数之前,表达式func()
未知.
However, when func
is declared with the return type placeholder auto
, then the declaration of func
depends on its definition, so the type of func
, and hence of the expression func()
, is not known until the function has been defined.
当您在类定义中内联定义一个类成员函数时,就好像该定义恰好出现在类定义的末尾(也就是说,函数体可能引用了用词法声明的名称<类定义中的em>稍后).这样做的结果和auto
的语义是,直到类定义结束之前,函数auto func
才真正被完全声明,因此,直到func()
的类型都无法知道然后.
When you define a class member function inline in the class definition, this is as if the definition were to appear right after the end of the class definition (that is, the function bodies may make reference to names that are lexically declared later in the class definition). The consequence of this and the semantics of auto
is that your function auto func
is not actually fully declared until the end of the class definition, and thus the type of func()
cannot be known until then.
这篇关于为什么尚未定义具有推导的返回类型的内联方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!