简体   繁体   English

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

[英]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 当我尝试在私有方法函数上使用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;}
};

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). 现在我的问题是,为什么编译器不在类的私有部分中查找,因为删除尾部返回类型或将私有部分置于masterMethod解决了问题( decltype(auto) [如果C ++ 14是允许]也是正确的自动返回类型扣除)。

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? 此外,当m1()m2()具有相同的返回类型时,删除decltype(m1())是不是很糟糕,这对我来说也是如此?

This is unrelated to both private and trailing return types. 这与private和尾随返回类型无关。

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 而g ++说

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. 唯一的解决方案是改变声明的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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