C++ template name mangling

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Fri Aug 15 18:55:43 PDT 2014


On 8/15/14, 1:53 PM, H. S. Teoh via Digitalmars-d wrote:
> On Fri, Aug 15, 2014 at 12:53:29PM -0700, Walter Bright via Digitalmars-d wrote:
>> Currently, D supports:
>>
>> 1. C++ function name mangling
>> 2. C++ namespace name mangling
>> 3. C++ class field and vtbl[] layout
>> 4. C++ function calling conventions
>>
>> But what is missing is name mangling to match C++ templates. This
>> makes it awkward and tedious to construct a D interface to a C++
>> template.
>>
>> Andrei has proposed that D support, for templates declared within an
>> extern(C++) block, C++ name mangling. This should not be difficult, it
>> should not break any existing D source code, and will enable limited
>> interaction with C++ templates from D.
>>
>> One nice side benefit is that no other language offers such support,
>> and given the increasing ubiquity of C++ template use, it would give
>> us a nice leg up.
>
> Sounds like an interesting idea.
>
> What are the limits to this, though? Obviously, anything involving
> D-only features can't possibly work, like alias parameters, typesafe
> variadics, etc..

The tighter integration the better. This is crucial to make D a good 
investment for Facebook going forward. It may as well be D's killer 
feature the same way C integration has been C++'s killer feature back in 
the day.

A few more details about this. Simple free function mangling should be 
the first step. The next step would be to allow full C++ object 
manipulation from D, using D rules and semantics. Consider the 
definition of std::string:

template <
   class charT,
   class traits = char_traits<charT>,
   class Alloc = allocator<charT>
 >
class basic_string {
   bool empty() const { ... }
   ...
private:
   ... state ...
};

That could be replicated in D as follows:

extern(C++)
struct basic_string(charT,
   traits = char_traits!charT,
   Alloc = allocator!charT)
{
     bool empty() const; // no definition!
           // generate mangled call to C++ function
     ...
private:
     ... state ...
}

The state/layout must be duplicated. The D compiler would generate 
proper mangled calls and even (in the future) proper constructor and 
destructor calls, which would take us to the holy grail - seamless C++ 
object manipulation from D. From the C++ side this is needed:

template class basic_string<char>;

That instructs the C++ compiler to make all methods of that 
instantiation available for linking. Then D would simply compile calls 
to them, achieving parity save for inlining. Inlining is important so 
probably in stage 3 we should allow inlining on the D side as well.


Andrei




More information about the Digitalmars-d mailing list