使用 decltype 作为成员函数返回类型时,声明顺序很重要

2024-03-29

为什么这有效:

template<typename Base, typename Acc>
struct Foo
{
    Base base;
    Acc acc;

    auto operator()(unsigned i) const -> decltype(acc(base(i)))
    { return acc(base(i)); }
};

这会产生编译器错误:

template<typename Base, typename Acc>
struct Foo
{
    auto operator()(unsigned i) const -> decltype(acc(base(i)))
    { return acc(base(i)); }

    Base base;
    Acc acc;    
};

错误:“base”没有依赖于模板的参数 参数,因此“base”声明必须可用 [-fpermissive]

这真的是标准的意图还是 GCC 4.8.1 的错误?


我找到了一个更短的演示示例:

#include <iostream>

struct Foo
{
    int x;

    auto getx() const -> decltype(x) // OK
    { return x; }

    auto gety() const -> decltype(y) // ERROR
    { return y; }

    int gety2() const // OK
    { return y; }

    int y;
};

int main(int argc, char* argv[])
{
    Foo f {1,2};
    std::cout << f.getx() << std::endl;
    std::cout << f.gety() << std::endl;
}

预计在函数声明之前仅声明成员。如标准第 §5.1.1 第 3 条所示:

如果声明声明了一个成员函数……[注意:仅事先声明的班级成员 声明可见。 ——尾注]

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 decltype 作为成员函数返回类型时,声明顺序很重要 的相关文章

随机推荐