Function templates do implicit conversions for their arguments

TommiT tommitissari at hotmail.com
Tue Jul 2 09:59:48 PDT 2013


This is a pretty big delta between C++ and D. It's going to 
surprise everybody coming from C++, especially when it says in 
TDPL (page 140) that: "However, having the language attempt 
combinatorially at the same time implicit conversions and type 
deduction is a dicey proposition in the general case, so D does 
not attempt to do all that".

D
---
struct Wrap(Gift)
{
     Gift gift;
}

struct Teddy
{
     int id;

     Wrap!Teddy getWrapped() @property
     {
         return Wrap!Teddy(this);
     }

     alias getWrapped this;
}

Gift tearOpen(Gift)(Wrap!Gift wrappedGift)
{
     return wrappedGift.gift;
}

void main()
{
     auto ted = Teddy(123);
     auto r = tearOpen(ted); // NOOOO! Teddy!
     assert(r == ted); // Phew, Teddy was implicitly gift-wrapped
                       // and we tore the wrap open, not Teddy.
}


C++
---
template <typename Gift>
struct Wrap
{
     Gift gift;
};

struct Teddy
{
     int id;

     operator Wrap<Teddy>()
     {
         return Wrap<Teddy>{*this};
     }
};

template <typename Gift>
Gift tearOpen(Wrap<Gift> wrappedGift)
{
     return wrappedGift.gift;
}

int main()
{
     Teddy ted (123);
     tearOpen(ted); // No matching function call to 'tearOpen'
}


This difference between D and C++ should be noted somewhere in 
the documentation with big red letters.


More information about the Digitalmars-d mailing list