struct constructors and function parameters

Adam Burton adz21c at gmail.com
Wed Nov 10 15:43:30 PST 2010


Simen kjaeraas wrote:

> Adam Burton <adz21c at gmail.com> wrote:
> 
>> 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
> 
> Wouldn't that be the opposite of what you were discussing earlier?
> alias this lets a struct behave as an or whatever, not the other way
> around.
> 
You've lost me. I think you are getting at the fact that alias this isn't 
exactly the same as structs using constructors for implicit casts. I was 
just acknowledging I have looked into it (I am using it for something else 
but that bug gets in my way :-(). That being said if you make the alias this 
a factory method for your implicit casts it could be used to do so. For 
example

struct D
{
    int i;
    alias implicitCast this;
    E implicitCast()
    {
        return E(i);
    }
}

struct E
{
    int i;
}

void main()
{
    E e = E(1);
    D d = D(2);
    e = d;
    writefln(to!string(e.i));   // 2
}

As stated by the bug this doesn't work for function parameters. With member 
variables it is ok though.

Mentioning our earlier discussion I don't see why the implicit casts 
couldn't be handled in the same manner as below.

interface A
{}

interface B
{}

class C : B, A
{}

void foo(A a){}
void foo(B b){}

void main()
{
    foo(new C());
}

test2.d(15): Error: function test2.foo called with argument types:
        ((C))
matches both:
        test2.foo(A a)
and:
        test2.foo(B b)



More information about the Digitalmars-d-learn mailing list