Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 518
mbed_dev Avatar asked Aug 20 '18 12:08

mbed_dev


People also ask

What does decltype return?

The decltype type specifier yields the type of a specified expression. The decltype type specifier, together with the auto keyword, is useful primarily to developers who write template libraries. Use auto and decltype to declare a function template whose return type depends on the types of its template arguments.

What is trailing return type C++?

The trailing return type feature removes a C++ limitation where the return type of a function template cannot be generalized if the return type depends on the types of the function arguments.

Why use trailing return types C++?

The trailing return type syntax allows you to put the function name before the arguments before the return type. This is a significantly better ordering than putting the return type first (which is why so many newer languages put the return type last as well).

What is a decltype in C++?

In the C++ programming language, decltype is a keyword used to query the type of an expression. Introduced in C++11, its primary intended use is in generic programming, where it is often difficult, or even impossible, to express types that depend on template parameters.


1 Answers

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.

like image 51
molbdnilo Avatar answered Oct 03 '22 16:10

molbdnilo