Can a function declaration be placed in an unnamed namespace?

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

Here is how I thought this 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. Should I include a definition in an unnamed namespace?

+6
c ++ namespaces
source share
3 answers

You must also define it in an anonymous namespace:

 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 if there is no cyclical dependency, I'm not sure what that value is. Just declare and define the function at a time.

+9
source share

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

This means that the declaration of your function refers to the namespace in the same way as if the namespace actually had a name. Thus, its definition must be in the same namespace: either declare, or define the function, or add the namespace {} environment around the definition (which works because all occurrences of the unnamed namespace in the translation unit belong to the same namespace) .

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

You probably also need to look at this topic:

Is static namespace superior to static?

By the way, why is this feature:

 void SkipWhitespace(const char *s); 

Why not this:

 void SkipWhitespace(std::string &s); 

??

+1
source share

All Articles