R. *_*des 19 c c++ 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)
}
Run Code Online (Sandbox Code Playgroud)
唯一的原因是"因为它使解析器变得更简单"和"因为标准是这样说的",还是有一个不明确的用途?
Oli*_*rth 17
这实际上是一个C问题,因为这种行为是直接从C继承的(尽管由于最令人烦恼的解析,它在C++中得到了更多的压力).
我怀疑答案(至少在C的上下文中)是,这允许您将函数声明的存在范围精确到适合它们的位置.也许这在C的早期是有用的.我怀疑任何人都这样做了,但为了向后兼容,它不能从语言中删除.
如果您需要使用名称与当前转换单元(源文件)中的内部(静态)函数或变量冲突的外部函数,这将非常有用.例如(愚蠢但它得到了重点):
static int read(int x)
{
return bar(x);
}
static int foo()
{
ssize_t read(int, void *, size_t);
read(0, buf, 1);
}
Run Code Online (Sandbox Code Playgroud)