【发布时间】:2017-02-19 16:27:53
【问题描述】:
#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 在定义之前就被使用了。为什么?
将推导的 auto 返回类型更改为 std::string 使其工作。
【问题讨论】:
-
内联函数定义就像你在类定义的末尾之后写的,所以在
static_assert处,函数还没有定义. -
@KerrekSB 但将返回类型更改为显式使其编译正常
-
当然,但
auto的全部意义在于从定义中推断出类型... -
当你明确返回类型时,函数的声明就足以知道返回类型。当返回类型为
auto时,编译器在声明时并不知道返回类型是什么;它必须等到函数定义,这会在稍后发生。 -
@Danra:是的。
decltype是关于(紧紧抓住)声明的类型。但是auto做出了依赖于定义的声明。