www.digitalmars.com Home | Search | C & C++ | D | DMDScript | News Groups | index | prev | next
Archives

D Programming
D
D.gnu
digitalmars.D
digitalmars.D.bugs
digitalmars.D.dtl
digitalmars.D.ide
digitalmars.D.dwt
digitalmars.D.announce
digitalmars.D.learn
digitalmars.D.debugger

C/C++ Programming
c++
c++.announce
c++.atl
c++.beta
c++.chat
c++.command-line
c++.dos
c++.dos.16-bits
c++.dos.32-bits
c++.idde
c++.mfc
c++.rtl
c++.stl
c++.stl.hp
c++.stl.port
c++.stl.sgi
c++.stlsoft
c++.windows
c++.windows.16-bits
c++.windows.32-bits
c++.wxwindows

digitalmars.empire
digitalmars.DMDScript
electronics




digitalmars.D - A solution to multiple opCasts

↑ ↓ ← "Simen Kjaeraas" <simen.kjaras gmail.com> writes:
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 =3D 42;
     }

     void opCast(ref string result)
     {
       result =3D "Text here";
     }

     void opCast(T)(ref T result)
     {
       result =3D data;
     }
   }

The compiler would then rewrite as follows:

   foo f;
   void bar(string s){}

   int a =3D cast(int)f; // becomes int a; f.opCast(a);

   bar(cast(string)f); // becomes string tmp; f.opCast(tmp);

   baz b =3D cast(baz)f; // becomes baz b; f.opCast(baz)(b);


As we can see, the function call introduces a temporary value, which mig=
ht  =

be
unwanted. Apart from that, I can't see any problems OTOH, but I'm sure  =

there are
some. Please do comment.

-- Simen
Apr 26 2008
↑ ↓ → "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"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. 
Apr 27 2008