April 26, 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
April 27, 2008
"Simen Kjaeraas" <simen.kjaras@gmail.com> wrote in message
news:op.t98lo3nc1hx7vj@spill04.lan...
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?

...

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.

----------------------------

No offense, but the idea is not new ;)  I'd imagine something like this would have to be implemented for opImplicitCast, unless Walter special-cases those and allows them to be overloaded on return type.  Which is weird.