How to define opCast from native types

Cherry cherry at dream.land
Fri Feb 7 03:06:05 PST 2014


Greetings

I need to cast from long to Integer (see the code below). But it 
seems D wants opCast to be a method and not a global template 
function. I know that I could define a constructor in Integer 
that takes a long as argument, but I do not want that to happen 
since it will enable silent conversion.

Can somebody tell me what is possible here? Also throw some light 
is to! template is looked at for cast operation. Could not find 
any relevant documentation. Please help.

Thanks and Regards
- Cherry

struct Integer {

   int _int;

   this(int that) {
     _int = that;
   }

   // Do not want to define a regular constructor for long
   // This would enable silent conversion

   // this(long that) {
   //   _int = cast(int) that;
   // }

}


// Does not work
T opCast(T, F)(F f) if( is(T == Integer) && is(F == long)) {
   Integer a;
   return a;
  }

void main()
{
   Integer foo;
   long ll;

   // works -- UFCS
   foo = ll.opCast!(Integer);

   foo = cast(Integer) ll;	// Does not compile

   // Integer bar = ll;          // Do not want this -- explicit 
cast is required

}


More information about the Digitalmars-d mailing list