Is there a use for function declarations inside fu

2019-01-09 12:15发布

问题:

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?

回答1:

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.



回答2:

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);
}


回答3:

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;
}


回答4:

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.