Is there a use for function declarations inside fu

2019-01-09 12:16发布

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?

4条回答
萌系小妹纸
2楼-- · 2019-01-09 12:27

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.

查看更多
叛逆
3楼-- · 2019-01-09 12:27

Are the sole reasons "because it makes the parser simpler" and "because the standard says so"

Yea, basically.

Everything that can be a function declaration, is a function declaration.

Unfortunately it's one of those "just is" cases.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-09 12:33

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):

static int read(int x)
{
    return bar(x);
}

static int foo()
{
    ssize_t read(int, void *, size_t);
    read(0, buf, 1);
}
查看更多
手持菜刀,她持情操
5楼-- · 2019-01-09 12:35

A function declaration inside another function hides other overloaded functions. e.g. Compiler error on Line 7

#include <iostream>

void f(int);
int main() {

    void f(char *);
    f(10);              // Line 7
    f("Hello world");
    return 0;
}

void f(int a) {
    std::cout << a;
}

void f(char *str) {
    std::cout << str;
}
查看更多
登录 后发表回答