Wherefore inline unnamed namespaces?

后端 未结 2 1680
天涯浪人
天涯浪人 2021-02-12 06:09

A quick one for the gurus: C++11 allows unnamed namespaces to be declared inline. This seems redundant to me; things declared in an unnamed namespace are already us

2条回答
  •  耶瑟儿~
    2021-02-12 06:45

    Here is one use that I have found:

    namespace widgets { inline namespace {
    
    void foo();
    
    } } // namespaces
    
    void widgets::foo()
    {
    }
    

    In this example, foo has internal linkage and we can define the function later on by using the namespace::function syntax to ensure that the function's signature is correct. If you were to not use the widgets namespace then the void foo() definition would define a totally different function. You also don't need to re-open the namespace saving you a level of indentation.

    If there is another function called foo in the widgets namespace already then this will give you an ambiguity instead rather than a nasty ODR violation.

提交回复
热议问题