使用decltype作为成员函数返回类型时,声明顺序很重要 [英] Order of declaration matters when using decltype for member function return type

查看:439
本文介绍了使用decltype作为成员函数返回类型时,声明顺序很重要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这样工作:

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]

error: there are no arguments to ‘base’ that depend on a template parameter, so a declaration of ‘base’ must be available [-fpermissive]

标准或与GCC 4.8.1有关的错误?

Is that really intended by the standard or a bug with GCC 4.8.1?

我发现了一个更简单的示例:

I found an even shorter example for demonstration:

#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节所示:

It is expected to have only members declared prior to the function declaration. As seen in §5.1.1 bullet 3 of the standard :


如果声明声明了一个成员函数... [注意:声明之前
的类成员是可见的。 -end note]

If a declaration declares a member function … [ Note: only class members declared prior to the declaration are visible. —end note ]

这篇关于使用decltype作为成员函数返回类型时,声明顺序很重要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆