Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
753 views
in Technique[技术] by (71.8m points)

c++ - decltype in class method declaration: error when used before "referenced" member is declared

Consider the following code:

struct test {    
    auto func() -> decltype(data) {}  // ERROR

    int data;
};

int main() {
    test t;
    t.func();
}

It gives the following error:

main.cpp:2:29: error: 'data' was not declared in this scope
     auto func() -> decltype(data) {}

However, if I place data above func(), it gives out no error (live code):

struct test {    
    int data;

    auto func() -> decltype(data) {}
};

...

And so my question is, why is decltype not considering members declared after it (when decltype is used in a method declaration, not in the definition)? I also want to know if there are any change in this behavior in future iterations of the language standard.


Please note that I'm asking this because I was expecting decltype to behave differently. My coding convention is to place class data members below the class functions. Surely this different behavior would affect how I organize my class members. I would be very grateful if you can provide any workaround that would preserve my coding convention. See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The trailing return type is part of the member function declaration, which does not have access to data members or member functions declared after it, unlike the member function definition, which does. I am not aware of any change in this behaviour in C++14.

See 3.4.1-7 of the C++11 standard, Unqualified name look-up:

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...

(emphasis mine)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...