extern(C++, ns)

Walter Bright via Digitalmars-d digitalmars-d at puremagic.com
Sun Jan 3 09:53:38 PST 2016


On 1/3/2016 9:14 AM, Marc Schütz wrote:
> On Sunday, 3 January 2016 at 16:18:13 UTC, Walter Bright wrote:
>> No. If D is to support C++ namespaces, it has to support declaring the same
>> identifier for different purposes in different namespaces. C++ namespaces have
>> different scopes in C++. Doing anything else would make it impossible to
>> connect to perfectly legitimate C++ programs. The WHOLE POINT of C++
>> namespaces is to support declaring the same identifier in different namespaces.
>
> Yes, but the point of `extern(C++, ns)` is NOT to achieve the same in D! D has
> its own mechanisms for that, primarily the module system, as well as hacks like
> static structs. And I don't see how Manu's suggestion would make it impossible
> to link to some C++ programs. Can you give an example?

I did. You quoted it below :-)


>>> This would solve a lot of awkward issues.
>>
>> It'd be a river of bug reports, because sure as shootin', people are going to
>> try to interface to this C++ code:
>>
>>   namespace ns1 { int identifier; }
>>   namespace ns2 { int identifier; }
>>
>> And why shouldn't they? It's correct and legitimate C++ code.
>
> I guess in reality this would not be a frequent thing. Most real C++ code will
> have both instances of `identifier` declared in different header files, and D's
> modules will usually closely mirror those, so they will end up in different
> modules on the D side.

My experience with "who would ever write such code" is they exist and you cannot 
wish them away. In a more general case, we should allow as much C++ 
compatibility as we can, because every shortcoming will be complained about at 
length. And, as Manu pointed out, one is often not able to adjust the C++ side 
of the bridge.

Besides, this isn't even an edge case. It's what C++ namespaces are for.


> In the rare case

That's a vast assumption. Manu is one programmer out of a million.


> the same identifier actually does appear twice in the same
> module, static structs can be used:
>
> struct ns1 {
>      extern(C++, ns1):
>      int identifier;
> }
> struct ns2 {
>      extern(C++, ns2):
>      int identifier;
> }

Offhand, I can't think at the moment why that wouldn't work, but using structs 
as C++ namespaces did have problems I don't recall at the moment, and:

1. It's ugly.
2. You're an expert, and it's wrong - the fields need to be 'static'. How will 
others fare?
3. I suspect that this ugly thing will become "best practice", and we won't be 
able to fix it in a backwards compatible way.
4. Structs carry other baggage with them, such as 'init' fields, TypeInfo's, 
default member functions, etc.
5. I don't share the opinion that a C++ namespace introducing a scope, just as 
it does in C++, is something weird and unexpected.


More information about the Digitalmars-d mailing list