How to define opCast from native types

Ali Çehreli acehreli at yahoo.com
Fri Feb 7 09:56:29 PST 2014


On 02/07/2014 03:06 AM, Cherry wrote:

 > struct Integer {
 >
 >    int _int;
 >
 >    this(int that) {
 >      _int = that;
 >    }
 >
 >    // Do not want to define a regular constructor for long
 >    // This would enable silent conversion

That's not true.

 >    // 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

The line above is an explicit object construction. That's why D allows 
that syntax. Unlike C++, there is no implicit conversion when passing to 
a function:

void func(Integer i)
{}

   func(1L);  // Does not call the constructor

 > }

To add to what w0rp said, I've experimented with overloading std.conv.to 
for my types:

import std.conv;

Integer to(T = Integer)(long l)
{
     return Integer(l);
}

     func(1L.to!Integer);  // Compiles


I am not sure how good an idea it is because my overload is not a part 
of std.conv.

Ali

P.S. There is also the D.learn newsgroup.



More information about the Digitalmars-d mailing list