Is there any good reason why C++ namespaces are "closed" in D?

Walter Bright newshound2 at digitalmars.com
Fri Aug 3 21:49:53 UTC 2018


On 8/3/2018 3:58 AM, Atila Neves wrote:
> With your mixin template technique everything ends up in the global namespace of 
> the moduel making the C++ declarations.

Right, but that's what you wanted!

> I would only be able to alias a nested 
> namespace once, since the code below obviously won't work:
> 
>     mixin CppNamespace0!() x;
>     alias chrono = x.std.chrono;
>     mixin CppNamespace1!() y;
>     alias chrono = y.std.chrono;

Try this:


      mixin template X() {         // boilerplate prefix

          extern (C++, std) extern(C++, chrono) int foo();   // original line

      } mixin X!() x; alias foo = x.std.chrono.foo;  // boilerplate suffix



> I considered for a while whether or not this would be truly bad, and the more I 
> think about it the more convinced I am that Manu is right and there should be 
> _no_ scoping whatsoever in D regarding C++ namespaces. We have packages and 
> modules, we can use those to put the C++ functions we declare in whatever 
> hierarchy we want.

I am puzzled. With:

   namespace std {
      namespace chrono {
          void foo();
      }
   }

   namespace std {
     namespace chrono {
          void bar();
     }
   }

you have stated that it is impractical for your translator to rewrite this as:

    namespace std {
      namespace chrono {
          void foo();
          void bar();
      }
   }

Ok, I get that. But it is practical to rewrite it as:

    module std.chrono;
    void foo();
    void bar();

?

 > I mean `std` should never be part of the fully qualified name of, for
 > instance, `core.stdcpp.exception.std.bad_exception`. It should just
 > be `core.stdcpp.exception.bad_exception` instead.

C++ recognizes that, too, which is why it has "using" declarations. D has the 
equivalent thing, "alias".

You can do things like:

     import std = core.stdcpp.exception;

and then refer to:

     std.bad_exception

or:

     import exception = core.stdcpp.exception;

     exception.bad_exception;

or whatever works best for one's project. Aliasing and import renaming (which 
are really just more aliasing) is very capable, and was designed for just these 
sorts of issues.


More information about the Digitalmars-d mailing list