Programming to Interfaces simplification
Steven Schveighoffer
schveiguy at yahoo.com
Mon Feb 24 10:59:32 PST 2014
On Mon, 24 Feb 2014 11:36:50 -0500, Frustrated <c1514843 at drdrb.com> wrote:
> http://dpaste.dzfl.pl/c25655e2dfe9
>
> The code above simplifies using interfaces as the programming
> object. It allows one to program the derived classes as if they
> were not part of an abstraction by mapping the abstracted virtual
> methods to concrete methods.
>
> e.g.,
>
> class WindowsGui : iGui
> {
> WindowsButton _button;
> @property WindowsButton button(WindowsButton b) { return
> (_button = b); }
>
> mixin(Fixup!(WindowsGui, iButton, WindowsButton));
> }
>
> instead of
>
> class WindowsGui : iGui
> {
> WindowsButton _button;
> @property iButton button(iButton b)
> {
> assert(cast(WindowsButton)b !is null, `Invalid object
> type dependency mismatch! Type: `~b.classinfo.name~` Type
> Expected: WindowsButton`);
> auto bb = cast(WindowsButton)b;
> // do work with bb.
> }
> }
Nice work!
> One problem with the template is that b.classinfo.name returns
> the interface instead of the actual class.
Hm... classinfo (now typeid) should get the most derived type from an
instance. This may be a factor of it being an interface instance vs. a
class instance. A simple test:
Stevens-MacBook-Pro:~ steves$ cat testinterface.d
import std.stdio;
interface I
{
}
class C : I
{
}
void main()
{
I i = new C;
writeln(typeid(i).name);
writeln(typeid(cast(Object)i).name);
}
Stevens-MacBook-Pro:~ steves$ ./testinterface
testinterface.I
testinterface.C
Looks like that is the case. Note that classinfo is not part of the
language any more, and will likely be deprecated. typeid is the correct
mechanism to get the TypeInfo of a derived class.
I'm thinking this is incorrect, typeid should get the derived class type
IMO. It shouldn't be that difficult or costly for the compiler to do.
-Steve
More information about the Digitalmars-d-learn
mailing list