Implicit type conversion for function calls?

Jonathan M Davis jmdavisProg at gmx.com
Sun Jul 10 12:39:54 PDT 2011


On Sunday 10 July 2011 20:47:04 David Nadlinger wrote:
> On 7/10/11 3:29 PM, Simen Kjaeraas wrote:
> > I'm trying to have this sort of code compile:
> > 
> > ////////////////
> > struct Foo {
> > int data;
> > this(int n) {
> > data = n;
> > }
> > }
> > 
> > void bar(Foo f) {}
> > 
> > bar(3);
> > ////////////////
> > 
> > Is this even possible?
> 
> If I remember correctly, Walter said that this is a deliberate
> limitation the last time I asked (when implementing my units of
> measurement library). I think the intention is to avoid confusion about
> what is actually going on behind the scenes, like it is possible in C++
> with implicitly called constructors.

Yes. In C++, the compiler will do up to 3 conversions for you, so you can end 
up calling a very different function than you might have intended to. It's 
usually not a problem, but it can definitely lead to issues and can effectively 
be a form of function hijacking. So, D forces you to do the conversion 
yourself by constructing a temporary of the appropriate type or doing a cast 
or whatnot. I expect that if there is anything that allows you to get away 
with it (such as what Bearophile did), it's a bug.

The only exceptions to this are things which would allow for an implicit cast 
(such as alias this). There has been talk from time to time of adding an 
opImplicitCast, which would allow you to define when this sort of thing coudl 
happen (at least when you've defined the type being passed in), but it's never 
been added to the language, and I think that alias this is pretty much 
supposed to solve that problem, so I don't expect that it ever will.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list