struct constructors and function parameters

div0 div0 at sourceforge.net
Tue Nov 9 16:14:13 PST 2010


On 09/11/2010 23:57, Simen kjaeraas wrote:
> Adam Burton <adz21c at gmail.com> 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.
>
> Far as I know, that's not supposed to work, no. Guess it has to do with
> overloading:
>
> struct foo {
> this( int n ){}
> }
>
> void bar( foo f ) {}
> void bar( int n ) {}
>
> bar( 3 ); // which do I call?
>

This does work in C++.

As for D, dunno. There are arguments both ways and this is why C++ has 
the 'explicit' keyword. The 'explicit' keyword specifically stops the 
example compiling.

So they kinda work the same way but from opposite ends.

For me, I prefer the D way; in my code at work the 'explicit' keyword 
seems to confuse a lot of people.

-- 
My enormous talent is exceeded only by my outrageous laziness.
http://www.ssTk.co.uk


More information about the Digitalmars-d-learn mailing list