Type converter from build in to user type

jerro a at a.com
Thu Nov 29 19:24:14 PST 2012


On Friday, 30 November 2012 at 02:59:06 UTC, js.mdnq wrote:
> I have a struct I am trying convert from int's to the type. 
> Since I can't add a opCast overload to an int I don't know how 
> to do it. My opCast convertors in my class do not work for the 
> assignment operator:
>
>
> class myType
> {
>    opCast, opAssign
> }
>
> mytype = 3;
>
> Error that we can't convert an int to myType. While it's very 
> easy to go from a myType to whatever by writing a cast for 
> it(in the class), how do I go from an int to myType(in the 
> class)?
>
> For example, I can do
>
> mytype = mytype.opCast(3);
> or mytype.opAssign(3);
>
> but these are too verbose to be useful.

Why can't you use opAssign? This works fine:

class A
{
     void opAssign(int i)
     {
         writeln(i);
     }
}

auto a = new A();
a = 1;                 // prints 1



More information about the Digitalmars-d-learn mailing list