Anonymous namespaces: Are they really that great?

c++, namespaces, static

Solution

If the code in your namespace is too long, there's nothing to stop you doing this:

namespace {
    int foo(char* x) {
        return x[0] + x[1];
    }
}

namespace {
    int bar(char *x, char *y) {
        return foo(x) + foo(y);
    }
}

In C++03 the practical advantage of using an unnamed namespace is precisely that the contents have external linkage, (but are still invisible outside the TU because there's no way to refer to them). Template parameters can't have internal linkage:

namespace {
    int foo(const char* x) {
        return x[0] + x[1];
    }
}

static int foo2(const char *x) {
    return x[0] + x[1];
}

template <int (*F)(const char*)>
void baz(const char *p) {
    F(p);
}

int main() {
    baz<foo>("ab");   // OK
    baz<foo2>("ab");  // not valid
}

Problem

I have been using the `static` keyword a long time for defining internal linkage. Later, I switched to the C++ style of wrapping local things in anonymous namespaces. However, now when I have worked with anonymous namespaces for some years, I start to think that `static` keyword is a lot easier to work with! A common problem is that I have this pattern: ``` namespace { // ...five pages of code... } // namespace ``` To see if a certain function has internal or external linkage, I now have to scroll a lot, as opposed to the old C style where I could just check if the function/object had `static` in front of it. I know there are things anonymous namespaces do that `static` can't - hide typedefs - but personally I'm not really very interested in that, anyway. What are your take on this? Is the win of anonymous namespaces that great that it warrants the decreased readability? Or am I all out wrong?

Original source

Related problems