Why is namespace composition so rarely used?

前端 未结 4 1722
不思量自难忘°
不思量自难忘° 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:20

    Mostly I wonder what the benefits would be (as Raymond Chen says, every feature starts with -100 points). However, I have a counterpoint to offer: Luabind, which does use something that looks like this. See luabind/object.hpp, which essentially says:

    namespace luabind {
      namespace adl {
        class object {
        };
      }
      using adl::object;
    }
    

    From the name alone we can infer the motivation: to support argument-dependent lookup. Given what the user knows as a luabind::object, which is actually a luabind::adl::object, related functions will be discovered automatically by the compiler from the luabind::adl namespace. Yet those functions, which the user may not need to know about in a very explicit way, do not "pollute" the main luabind namespace. So that's nice, I guess.

    But you know what's not nice? Forward declaring one of these classes. This fails:

    namespace luabind { class object; }
    

    You need to do this instead:

    namespace luabind { namespace adl { class object; } }
    

    Thus the abstraction quickly leaks, as the user does need to know about this magic adl namespace after all.

提交回复
热议问题