为什么我的类静态自动函数的类型不能在类范围内推导出来?

zne*_*eak 10 c++ c++14

我正在尝试获取auto函数的返回类型.这有效:

auto foo(int bar)
{
    return 0;
}

typedef std::result_of<decltype(foo)> foo_t;
Run Code Online (Sandbox Code Playgroud)

好的,这是下一步:static auto在类范围中获取函数的返回类型.这也有效:

struct Foo
{
    static auto foo(int bar)
    {
        return 0;
    }
};

typedef std::result_of<decltype(Foo::foo)> foo_t;
Run Code Online (Sandbox Code Playgroud)

但这不起作用:

struct Foo
{
    static auto foo(int bar)
    {
        return 0;
    }

    typedef std::result_of<decltype(Foo::foo)> foo_t;
};
Run Code Online (Sandbox Code Playgroud)

GCC说"错误:在扣除'auto'之前使用'static auto Foo :: foo(int)'",Clang说"在推定返回类型之前,函数'foo'不能在定义之前使用".为什么?

Joh*_*nck 14

虽然编写代码的方式使得它看起来成为可能,但foo()只能在完全定义类之后才能处理类内定义.就像你写的那样:

struct Foo
{
    static auto foo(int bar);

    typedef std::result_of<decltype(Foo::foo)> foo_t;
};

auto Foo::foo(int bar)
{
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

的定义foo()被允许使用在定义的类型class Foo,包括foo_t,这将是圆形的.因此,定义class Foo不允许使用其成员函数的定义 - 只有它们的声明.

换句话说,您假设代码是从上到下完全评估的.它不是.