Is there any good reason why C++ namespaces are "closed" in D?
Walter Bright
newshound2 at digitalmars.com
Fri Jul 27 22:50:20 UTC 2018
On 7/27/2018 10:28 AM, Atila Neves wrote:
> But all I'm trying to do here is tell the D
> compiler how to mangle symbols.
Namespaces have semantic implications, too, such as overload resolutions. A
namespace introduces a new scope, not just a mangling.
> But why does this not compile?
> extern(C++, ns) { void foo(); }
> extern(C++, ns) { void bar(); }
For the same reason that:
struct ns { void foo(); }
struct ns { void bar(); }
doesn't. Being able to crack open a scope and stuff more symbols into it at any
point in a program is just madness :-)
However, one can do:
------ module A ---------
extern(C++, ns) { void foo(); }
------ module B ---------
extern(C++, ns) { void bar(); }
------ module C ---------
import A,B;
ns.foo(); // error, A.ns or B.ns?
A.ns.foo(); // ok
Because the compiler sees A.ns as utterly distinct from B.ns, although the
mangling will be the same - any conflicts will be the linker's problem.
This is how, for example, extern(C) declarations can exist in many files.
> Such a program can easily do that to `extern(C)`, but doing that to
`extern(C++)` is for some reason not allowed.
It is allowed. Just not reopening the same namespace.
Namespaces are a botch in C++, and it is understandable that C++ code bases
naturally have grown willy-nilly to utterly ignore any encapsulation principles.
It's analogous to how monkey-patching in Ruby was seen initially as a cool
feature, but eventually people learned the hard way what a disastrous idea it was.
More information about the Digitalmars-d
mailing list