简体   繁体   中英

private method as trailing return type (decltype)

When I am trying to use decltype() on a private method function I get the error that the private method error: 'm1' has not been declared in this scope

#include <stdint.h>

class C
{
public:
    C()=default;
    ~C()=default;

    auto masterMethod(int opMode) ->decltype(m1())
    {
        switch(opMode)
        {
        case 1:
                return m1(); break;
        case 2:
                return m2(); break;
        default:
                return m1(); break;
        }
    }
private:
    int m1() {return 1;}
    int m2() {return 2;}
};

Now my question is, why the compiler does not lookup in the private section of the class, because removing the trailing return type or putting the private section on top of masterMethod solves the problem ( decltype(auto) [in case C++14 is allowed] would be also correct with its automatic return type deduction).

Furthermore, is it bad behaviour when removing the decltype(m1()) when m1() and m2() have the same return-type, as this would do it for me too?

This is unrelated to both private and trailing return types.

The problem here is that while all declared names in a class are in scope in the bodies of its member functions, the trailing type is not part of the function body - it's part of the prototype.

Here is a much smaller example of the same problem:

struct A
{
    T f();
    using T = int;
};

And g++ says

error: 'T' does not name a type

But this is fine:

struct A
{
    using T = int;
    T f();
};

The only solution is to change the order of declaration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM