问题
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?
回答1:
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; }
};
回答2:
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
Xoutside of a member function body or nested class definition shall be declared in one of the following ways:
— before its use in classXor be a member of a base class ofX(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;
};
来源:https://stackoverflow.com/questions/27371102/how-to-use-auto-return-and-decltype-when-class-members-involved-with-c11