简体   繁体   中英

Is it possible to put a function declaration within an unnamed namespace?

I have a file with a set of functions. For one of the functions, I want to write a helper function which basically takes a char * and skips all whitespaces.

Here's how I thought it should be done:

namespace {
    const int kNotFound = -1;

    void SkipWhitespace(const char *s); // forward declaration - doesn't seem to work?
}

void foo(const char *s1, const char *s2) {
    // do some stuff

    SkipWhitespace(s1);
    SkipWhitespace(s2);

    // continue with other stuff
}

void SkipWhitespace(const char *s) {
    for (; !isspace(s); ++s) {}
}

But this gives me a compiler error. Do I need to put the definition within the unnamed namespace?

You have to define it in the anonymous namespace as well:

namespace {
    ...
    void SkipWhitespace(const char *s); // forward declaration - doesn't seem to work?
}

void foo(const char *s1, const char *s2) {
    ...
}

namespace {
    void SkipWhitespace(const char s*) {
        for (; !isspace(s); ++s) {}
    }
}

But unless there is a cyclic dependency, I'm not sure what the value of this is. Just declare and define the function in one go.

An unnamed namespace behaves as if it was replaced with a namespace with a uniquely generated name immediately followed by a using directive.

This means that your function declaration belongs to a namespace exactly as if the namespace actually had a name. As such, its definition should live in the same namespace : either simultaneously declare and define the function, or add an enclosing namespace {} around the definition (which works because all occurrences of the unnamed namespace in a translation unit refer to the same namespace).

namespace {

void SkipWhitespace(const char s*) {
    for (; !isspace(s); ++s) {}
}

}

You probably need to see this topic as well:

Superiority of unnamed namespace over static?

BTW, why this function:

void SkipWhitespace(const char *s);

Why not this:

void SkipWhitespace(std::string &s);

??

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM