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

核能气质少年 提交于 2019-12-12 23:48:25

问题


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 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;        
};


来源:https://stackoverflow.com/questions/27371102/how-to-use-auto-return-and-decltype-when-class-members-involved-with-c11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!