Polymorphism in regular variadic function
Bill Baxter
dnewsgroup at billbaxter.com
Tue Dec 5 16:20:08 PST 2006
Thanks Jarrett,
This TypeInfo_Class thing seems to be undocumented.
Incidentally it's a piece of cake with a variadic template, I just
wanted to see try it with a regular function first before going all
templatey.
I haven't tried your code, but it seems like your cast to Object in the
second suggestion is not going to be safe if the thing really isn't an
Object. The following cast to Foo will try to do some vtable stuff I
guess, and that could result in a bad memory access, no?
--bb
Jarrett Billingsley wrote:
> "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.
>
>
--bb
More information about the Digitalmars-d-learn
mailing list