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

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Aug 1 17:24:50 UTC 2018


On Wednesday, August 1, 2018 4:02:39 AM MDT Walter Bright via Digitalmars-d 
wrote:
> On 7/31/2018 1:12 AM, Manu wrote:
> > Given your favourite example:
> > ----
> > module a;
> > extern(C++, ns) void foo();
> > ----
> > module b;
> > extern(C++, ns) void foo();
> > -----
> > module c;
> > import a, b;
> > foo(); // error: ambiguous
> > ns.foo(); // error, ambiguous (obviously)
> > a.ns.foo(); // naturally, this works... it's the D module that
> > correctly organises the symbol. 'ns' is worthless here
>
> You can write it like this:
>
> ----
> module a;
> extern(C++, ns) void foo();
> alias foo = ns.foo;
> ----
> module b;
> extern(C++, ns) void foo();
> alias foo = ns.foo;
> -----
>
> import a,b;
> a.foo();  // calls a.ns.foo()
> b.foo();  // calls b.ns.foo()

Not to say that that can't work, but I have to say that it seems pretty ugly
if using extern(C++, NS) requires a bunch of aliases just to use symbols
normally. If the namespace were just part of the mangling, none of those
aliases would be necessary. All in all, it just seems like having the
namespaces add scoping just gets in the way - especially when they would
normally get the necessary scoping from being put into separate D modules.

Reading through this thread, and thinking about the issue, I don't see any
advantage to the current behavior over having it just affect mangling other
than the fact that that's how it currently works. All of the potential
complaints that you talk about seem like they at least _should_ be a
non-issue given that folks don't complain that way about D's module system
for non-C++ functions - but it's certainly true that even engineers aren't
always logical or reasonable.

However, if we were discussing a DIP for implementing namespaces for C++,
based on my current understanding of the matter, I'd definitely argue that
extern(C++) with namespaces should just affect mangling, since that approach
seems much more straightforward and much more in line with how other
languages are handled, particularly since the scoping aspect is already
going to be handled by D's module system anyway. As it stands, it just seems
like the language is forcing that all C++ functions be put inside of structs
to namespace them on top of them being put into a module. And that's
downright awkward, even if it can work. Certainly, it does come across like
you didn't trust the D module system to do its job for some reason.

- Jonathan M Davis





More information about the Digitalmars-d mailing list