templates
Steven Schveighoffer
schveiguy at yahoo.com
Mon Apr 19 19:47:03 PDT 2010
Ellery Newcomer Wrote:
> On 04/19/2010 02:16 PM, Steven Schveighoffer wrote:
> >
> > What you are looking for is a conversion from compile-time interface to
> > runtime interface. The only drawback is, you can't go backwards (from a
> > runtime interface to a compile-time).
>
> That hurts. The thing is, I'm eventually going to need to get that T
> back so I can access the non-common parts of it.
This is possible, via dynamic casting:
IW x;
if(auto wofT = cast(WByVal!T)x)
{
wofT._t.specializedMethod(); // need to expose _t in the class definition
}
If you need to figure out what type the IW is, you can do a switch on the classinfo. However, bottom line is, when you want to access a compile-time interface, you need to know about that type during compile time. So for instance if you add another type that can be wrapped by IW, you need to add another case statement for that type. Compile-time means the compiler has to know about everything, so there is no abstraction, everything must be concrete.
RTTI can do some incredible things, and I hope D can join the ranks of languages like C# and Java with a full runtime reflection capabilities.
> The T types already correspond to an enum, so the interface could look like
>
> interface IW{
> Type type();
> int foo(int);
> }
>
> then whenever I want T, I can just test type and perform a cast.
You can get this info via the classinfo, it's already there.
> Now I'm thinking of how to express that mapping in a centralized
> function or template or whatever, and I think I'm back where I started.
> Oh well. I'm probably going to have to write out each case longhand anyways.
Yes, each case must be explicitly handled. There is no generic way to do it! It is one of those things that seems like it should work, but if you ever try to solve it, you realize why it doesn't ;)
> It probably isn't important, but aren't dynamic casts rather expensive?
I wouldn't call them rather expensive, dynamic casts aren't particularly cheap, but they might be your only option. I would cache any dynamic cast so you aren't doing it over and over again.
If you want the absolute best speed, you will have to implement your own type of "dynamic cast" instead of using D's class/interface system, similar to what bearophile stated.
-Steve
More information about the Digitalmars-d-learn
mailing list