Anonymous namespaces: Are they really that great?

前端 未结 3 1397
一向
一向 2021-02-05 12:15

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.

3条回答
  •  醉酒成梦
    2021-02-05 12:53

    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 
    void baz(const char *p) {
        F(p);
    }
    
    int main() {
        baz("ab");   // OK
        baz("ab");  // not valid
    }
    

提交回复
热议问题