struct constructors and function parameters

Adam Burton adz21c at gmail.com
Tue Nov 9 16:32:16 PST 2010


Jonathan M Davis wrote:

> On Tuesday, November 09, 2010 15:48:27 Adam Burton wrote:
>> Hi,
>> should the below work?
>> 
>> struct A
>> {
>>     public this(B b) {}
>> }
>> 
>> struct B {}
>> 
>> void foo(A a) {}
>> 
>> void main()
>> {
>>     B b;
>>     foo(b);     // Fails
>> }
>> 
>> The constructor parameter doesn't need to be a struct, it could be an
>> int. The workaround is to explicity call the constructor.
> 
> It should _not_ work. D does not support implicit conversions like that.
> You might be able to get it work with alias this, but that would be very
> different from expecting the compiler to cast a B to an A using A's
> constructor in order to call a function. C++ does that sort of thing all
> the time, but it can make it very hard to figure out which function
> overload is actually being called and why. It can be quite error prone.
> So, D is much pickier.
> 
> You should look at http://www.digitalmars.com/d/2.0/function.html -
> particularly the section on overloading. Generally, types must match
> exactly when calling a function. There is some leeway with some of the
> primitive types and if there is no ambiguity class objects can be
> implicitly cast to a base class in a function call, but there certainly
> isn't anything for structs, since they don't have inheritance.
> 
> - Jonathan M Davis
I figured that was the case I just wanted to confirm :-)

I looked into alias this and it does indeed work, unless the alias is to a 
function. That has been reported as a bug though 
http://d.puremagic.com/issues/show_bug.cgi?id=2814


More information about the Digitalmars-d-learn mailing list