Is there any good reason why C++ namespaces are "closed" in D?
Atila Neves
atila.neves at gmail.com
Fri Jul 27 17:28:53 UTC 2018
I understand that being able to "reopen" namespaces in C++ is
contentious - anybody can add to the `std` namespace in their own
code. D doesn't have anything like it, and instead has packages
and modules. So far, so good.
But why does this not compile?
extern(C++, ns) { void foo(); }
extern(C++, ns) { void bar(); }
I could maybe understand the limitation if those functions had
bodies since we'd be importing the namespace functionality from
C++ in a sense (and even then I'm not sure it's a big enough
deal). But all I'm trying to do here is tell the D compiler how
to mangle symbols.
Why would this matter? Imagine a project that parses C++ headers
and translates them to D declarations. Imagine that project is
trying to parse `#include <vector>`. There will be many, many
instances of `namespace std` in there, but such a
not-so-hypothetical program can't just go through them and open
and close `extern(C++, std)` as it goes along. Such a program can
easily do that to `extern(C)`, but doing that to `extern(C++)` is
for some reason not allowed.
(is there even any semantic difference? extern(C) for a 2nd time
is just reopening the global namespace!)
One could simply manually `pragma(mangle)` everything up the
wazoo, but unfortunately that doesn't work for templates, which,
as it turns out, is pretty much everything inside the `std`
namespace.
My only solution is to keep track of all namespaces at all times
and then sort the declarations by namespace, which:
1) Is incredibly tedious
2) Might cause problems with the order of declarations,
especially if macros are involved.
I can only assume nobody has tried calling a large C++ library
from D (Qt doesn't count, no namespaces). Imagine manually
organising namespaces in one huge bindings file instead of being
able to copy the file layout of the C++ headers!
Sigh.
Atila
More information about the Digitalmars-d
mailing list