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 decla开发者_如何学编程ration - 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);
??
精彩评论