私有方法作为尾随 return 类型 (decltype)

private method as trailing return type (decltype)

当我尝试在私有方法函数上使用 decltype() 时,我收到私有方法 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;}
};

现在我的问题是,为什么编译器不在 class 的私有部分中查找,因为删除尾随 return 类型或将私有部分放在 [=14= 之上] 解决了问题(decltype(auto) [在允许 C++14 的情况下] 其自动 return 类型推导也是正确的。

此外,当 m1()m2() 具有相同的 return 类型时删除 decltype(m1()) 是否是不良行为,因为这对我来说也是如此?

这与 private 和尾随 return 类型无关。

这里的问题是,虽然 class 中所有声明的名称都在其成员函数的 bodies 范围内,但尾部类型不是函数体——它是原型的一部分。

这是同一问题的一个小得多的例子:

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

g++ 表示

error: 'T' does not name a type

但这很好:

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

唯一的解决办法是改变声明的顺序。