Order of declaration matters when using decltype for member function return type

StackOverflow https://stackoverflow.com/questions/23136632

  •  05-07-2023
  •  | 
  •  

Вопрос

Why does this work:

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

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

and this gives a compiler error:

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

    Base base;
    Acc acc;    
};

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

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;
}
Это было полезно?

Решение

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

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top