[cfe-dev] Using isa & co with custom class hierarchy

Victor Zverovich victor at zverovich.net
Wed Aug 25 09:33:34 PDT 2010


Sorry,  'classof' shouldn't be virtual itself of course.
The problem is that B::classof(const A *) always return true in your
implementation, so llvm::isa<B>(a)returns true as well.
To make it work as you expect you should return true only if an
argument to B::classof(const
A *)is a pointer to class B or its subclass.
This can be done e.g. using a type field or a virtual function returning
type identifier or dynamic_cast though if you use the latter you don't need
llvm::isa. You can have a look at how classof is implemented in clang's AST.

Victor

On Wed, Aug 25, 2010 at 5:10 PM, Victor Zverovich <victor at zverovich.net> wrote:

Hi Jan,
>
> I think 'classof' should be virtual for isa<> and friends to work. In
> addition you can provide a static 'classof' for the same class that will
> speed up the cases like isa<A>(a) and isa<A>(b).
>
> Regards,
> Victor
>
> On Wed, Aug 25, 2010 at 4:02 PM, Jan Bierbaum <s3306700 at inf.tu-dresden.de>wrote:
>
>> Hi!
>>
>> I hope I'm not too OT with that question, but Clang makes extensive use
>> of this mechanism so maybe somebody can help me.
>>
>> LLVM provides isa<>, cast<> and so on. Recently I tried to make use of
>> this for my own class hierarchy, but failed.
>>
>> >From the documentation and examples in Clang's code I figured that the
>> only thing to do was add a static method 'classof' to any involved class
>> with a parameter that will match any parent class. Then inside this
>> method do any checks necessary and return 'true' if the current instance
>> is indeed of the type given.
>>
>> But when I do this I get 'true' for any 'isa<>' I try!?
>>
>> Attached is a small example that outputs the following:
>>
>> | $ ./a.out
>> | isa<A>(a) = 1
>> | isa<B>(a) = 1
>> | isa<B>(b) = 1
>> | isa<A>(b) = 1
>>
>> What I would expect instead is the second line to yield false/0, since a
>> is an instance of class A which "is" no B.
>>
>> Can somebody please give me a hint on what I'm doing wrong?
>>
>>
>> Regards, Jan.
>>
>> _______________________________________________
>> cfe-dev mailing list
>> cfe-dev at cs.uiuc.edu
>> http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20100825/1c7cd61d/attachment.html>


More information about the cfe-dev mailing list