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
249 views
in Technique[技术] by (71.8m points)

c++ - Is there a use for function declarations inside functions?

We can declare functions inside functions (I wanted a local variable, but it parses as a function declaration):

struct bvalue;
struct bdict {
    bdict(bvalue);
}
struct bvalue {
    explict operator bdict() const;
}
struct metainfo {
    metainfo(bdict);
}
void foo(bvalue v) {
    metainfo mi(bdict(v)); // parses as function declaration
    metainfo mi = bdict(v); // workaround
                            // (this workaround doesn't work in the presence of explicit ctors)
}

Are the sole reasons "because it makes the parser simpler" and "because the standard says so", or is there an obscure use for this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is really a C question, because this behaviour was inherited directly from C (although it gets much more press in C++ because of the most vexing parse).

I suspect the answer (in the context of C, at least) is that this allows you to scope the existence of your function declarations to precisely where they're needed. Maybe that was useful in the early days of C. I doubt anyone does that any more, but for the sake of backward compatibility it can't be removed from the language.


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

...