Polymorphism in regular variadic function
Jarrett Billingsley
kb3ctd2 at yahoo.com
Mon Dec 4 20:05:22 PST 2006
"Bill Baxter" <wbaxter at gmail.com> wrote in message
news:el2iq4$2gb3$1 at digitaldaemon.com...
> Is there any way to check if an argument is type T or anything derived
> from it using the TypeInfo?
>
> Basically I want this:
>
> class Foo { int x = 3; }
> class Bar : Foo { long y = 4; }
>
> void printargs(...)
> {
> printf("%d arguments\n", _arguments.length);
> for (int i = 0; i < _arguments.length; i++)
> { _arguments[i].print();
>
> // Want to accept Foo or anything derived from Foo here!
> if (_arguments[i] == typeid(Foo))
> {
> Foo f = *cast(Foo*)_argptr;
> _argptr += Foo.sizeof;
> printf("\t%p\n", f);
> }
> else
> assert(0);
> }
> }
>
>
> --bb
Heheh.. I did something like:
TypeInfo ti = _arguments[i];
TypeInfo_Class tic = cast(TypeInfo_Class)ti;
if(tic)
{
ClassInfo ci = tic.info;
for( ; ci !is null; ci = ci.base)
if(ci == Foo.classinfo)
{
// it's derived, do what you will
}
if(ci is null)
{
// we got to the base without finding Foo,
// it's not derived from Foo
}
}
I wonder if there's any way to take advantage of the internal casting
functions (which are used whenever you do a dynamic downcast). Well, now
that I think about it, you might be able to replace the above condition
with:
if(tic)
{
Object o = va_arg!(Object)(_argptr);
Foo f = cast(Foo)o;
if(f !is null)
{
// it's a Foo
}
}
Which .. would probably work. Give it a shot.
More information about the Digitalmars-d-learn
mailing list