Why is namespace composition so rarely used?

前端 未结 4 1733
不思量自难忘°
不思量自难忘° 2021-02-18 23:57

In his book The C++ Programming Language (third edition) Stroustrup teaches to define individual components in their own namespace and import them in a general namespac

4条回答
  •  时光取名叫无心
    2021-02-19 00:08

    I guess because it reduces encapsulation. In your example, it's going to be a right pain when you write map_api to go to the api.h and import it into the api namespace. Having one big header api.h that imports every sub-namespace is not exactly include minimization.

    • map.h:

      namespace map_api { /* fns */ }
      
    • api.h:

      #include 
      namespace api { using map_api::map; }
      

    Or, considering other header layouts: if the imports into the api namespace happen in another file:

    • map_internal.h:

      namespace map_api { /* fns */ }
      
    • map_api.h:

      #include 
      namespace api { using map_api::map; }
      

    That's pretty painful too, having to split out the api into two files like that.

    The final possibility is doing it all in one file:

    • map.h:

      namespace map_api { /* fns */ }
      namespace api { using map_api::map; }
      

    In that case, what's the point I wonder of putting things in two namespaces that are on the same level of abstraction, if they're both equally exposed to all clients/includers..?

提交回复
热议问题