user defined implicit casts

Daniel Keep daniel.keep.lists at gmail.com
Fri Jul 27 22:14:04 PDT 2007



Ender KaShae wrote:
> ...
> now the problem is a lack of implicit casting for user defined types the Byte cannot be implicitly cast to byte, int, long etc. even though such a cast would make sense.  If implicit casting were allowed then a library could be fashioned with wrapper for all of the basic types and some less basic types such as cint, iint, fraction, radical, ifraction, cfraction, etc.  
> 
> my suggested syntax for overloading implicit casts is:
> 
> implicit type1 cast(type2 var);
> where type1 is the type casting to and type2 is the type casting from

Eww, ick.  First of all, you're overloading on return type, *and* you've
introduced a new keyword.  Sorry :)

D already allows you to define an explicit casting overload like so:

class Foo
{
    type1 opCast() { ... }
}

What has been suggested a few times is to make a new operator overload
that passes the result out using an out argument instead, which you
*can* overload on:

class Foo
{
    void opImplicitCast(out type1) { ... }
}

On the issue of using a global function (as opposed to a member
function), I'd rather get general type extensions, which would also
provide this as a sort of side effect:

bool isFoo(Object this)
{
    return (cast(Foo)this) !is null;
}

auto bar = (new Foo).isFoo;

> this syntax would allow non-member functions to be used, so that implicit casts can be overloaded in specific contexts 
> example:
> implicit int cast(long var){ return cast(int)var;}
> when you know that longs will never exceed the bound of ints

Ok, there's something very wrong about this.  Altering how casts happen
in particular contexts just strikes me as a very bad idea.  The problem
is that someone reading your code will need to go over it with a fine
tooth comb to work out what casts are *actually* doing at any given line.

That said, I *would* like to see implicit casts added to the language.

	-- Daniel



More information about the Digitalmars-d mailing list