为什么我的类静态自动函数类型不能在类作用域内推导?

11

我试图获取一个 auto 函数的返回类型。这个代码可以正常工作:

auto foo(int bar)
{
    return 0;
}

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

好的,那么接下来就是:获取类作用域中 static auto 函数的返回类型。这里有一个同样适用的方法

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

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

但是这不起作用

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

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

GCC 报错: "error: use of 'static auto Foo::foo(int)' before deduction of 'auto'", Clang 报错: "function 'foo' with deduced return type cannot be used before it is defined"。为什么?


我认为你想要写的是 std::result_of<decltype(&foo)(int)>::type,对吗? - O'Neil
@O'Neil,我很有可能完全不知道那是怎么工作的... - zneak
这是CWG2335的主题。 - Davis Herring
1个回答

16

尽管您编写的代码方式使其看起来可能,但类内定义的foo()只能在类完全定义后才能被处理。这就像您写了这样的代码:

struct Foo
{
    static auto foo(int bar);

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

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

foo()的定义允许使用在class Foo中定义的类型,包括可能形成循环引用的foo_t。因此,class Foo的定义不允许使用其成员函数的定义,只能使用它们的声明。

换句话说,你假设代码从上到下完全被评估,但实际情况并非如此。


据我所知,这是正确的,但“您假设代码从顶部到底部完全评估”有点不公平。 - zneak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接