函数内部的函数声明有用途吗?
我们可以在函数内部声明函数(我想要一个局部变量,但它解析为函数声明):
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)
}
唯一的原因是“因为它使解析器更简单”和“因为标准是这么说的”,或者这有什么隐晦的用途吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这实际上是一个 C 问题,因为这种行为是直接从 C 继承的(尽管由于最令人烦恼的解析,它在 C++ 中受到更多关注)。
我怀疑答案(至少在 C 的上下文中)是,这允许您将函数声明的存在范围精确地限制在需要它们的位置。也许这在 C 的早期很有用。我怀疑是否有人会再这样做,但为了向后兼容,它不能从语言中删除。
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.
如果您需要使用名称与当前翻译单元(源文件)中的内部(静态)函数或变量冲突的外部函数,那么它非常有用。例如(虽然很愚蠢,但它明白了要点):
It's useful if you need to use an external function whose name would conflict with an internal (static) function or variable in the current translation unit (source file). For instance (silly but it gets the point across):
另一个函数内部的函数声明隐藏了其他重载函数。例如第 7 行的编译器错误
A function declaration inside another function hides other overloaded functions. e.g. Compiler error on Line 7
是的,基本上。
所有可以作为函数声明的东西,都是函数声明。
不幸的是,这是“只是”的情况之一。
Yea, basically.
Everything that can be a function declaration, is a function declaration.
Unfortunately it's one of those "just is" cases.