How to use auto return and decltype when class members involved with c++11?

612 Views Asked by At

For example

struct A
{
    auto count() -> decltype(m_count) { return m_count; }
    int m_count;        
};

The above gets compilation error because m_count in decltype is not recognized. How to work around it? auto return and get the type from m_count must be used.

The code compiles when the order is changed

struct A
{
    int m_count;        
    auto count() -> decltype(m_count) { return m_count; }
};

but how do I get the first case to work?

2

There are 2 best solutions below

1
On BEST ANSWER

In C++, you can't use a name that hasn't been introduced (declared) in a declaration, including in a decltype for a trailing return type. So you must reorder your declarations :

struct A
{
    int m_count;
    auto count() -> decltype(m_count) { return m_count; }
};
0
On

The trailing return type is part of the member function declaration, and not the member function definition ([dcl.fct]/2). That's the reason why you can use m_count within the function body even when the data member follows the member function definition.

However, when used in a declaration, the name in question must be declared before its use.

§3.4.1/7 [basic.lookup.unqual]

A name used in the definition of a class X outside of a member function body or nested class definition shall be declared in one of the following ways:
— before its use in class X or be a member of a base class of X (10.2), or
...

In your case, you need to place the declaration of m_count ahead of count(); or if you have access to a C++14 compiler, you can omit the trailing return type altogether.

struct A
{
    auto count() { return m_count; } // OK in C++14
    int m_count;        
};