unnamed namespace

后端 未结 4 860
北荒
北荒 2020-12-10 04:03

What does it exactly mean when the Standard states

$7.3.1.1/2 - \"The use of the static keyword is deprecated when declaring variables in a namesp

4条回答
  •  隐瞒了意图╮
    2020-12-10 04:11

    What does it exactly mean?

    Technically deprecated means that a future standard may remove the feature.

    In practice that isn't going to happen, because of the need to support old code.

    So in practice it means, "strongly discouraged".

    Example of superiority of unnamed namespace

    An unnamed namespace is generally superior because what you have in that namespace can have external linkage.

    In C++98 external linkage is necessary for things that can be template parameters, e.g., if you want to templatize on a char const*, it must be pointer to char that has external linkage.

    #include 
    
    // Compile with "-D LINKAGE=static" to see problem with "static"
    #ifndef LINKAGE
    #   define LINKAGE extern
    #endif
    
    template< char const* s >
    void foo()
    {
        std::cout << s << std::endl;
    }
    
    namespace {
        LINKAGE char const message[] = "Hello, world!";
    }  // namespace anon
    
    int main()
    {
        foo();
    }
    

    That said, it's a bit inconsistent that static isn't also deprecated for functions.

提交回复
热议问题