A solution to multiple opCasts
Simen Kjaeraas
simen.kjaras at gmail.com
Sat Apr 26 14:23:17 PDT 2008
I was thinking of the plans for multiple opCasts today, when inspiration
suddenly struck me. What if opCast saved its return value in a reference
parameter of the appropriate type instead? That way, normal overloading
rules
would kick in, and you could define as many opCasts as you want. For
instance:
struct foo
{
someType[] data;
void opCast(ref int result)
{
result = 42;
}
void opCast(ref string result)
{
result = "Text here";
}
void opCast(T)(ref T result)
{
result = data;
}
}
The compiler would then rewrite as follows:
foo f;
void bar(string s){}
int a = cast(int)f; // becomes int a; f.opCast(a);
bar(cast(string)f); // becomes string tmp; f.opCast(tmp);
baz b = cast(baz)f; // becomes baz b; f.opCast(baz)(b);
As we can see, the function call introduces a temporary value, which might
be
unwanted. Apart from that, I can't see any problems OTOH, but I'm sure
there are
some. Please do comment.
-- Simen
More information about the Digitalmars-d
mailing list