[LLVMdev] dyn_cast really doesn't like multiple inheritance

Argiris Kirtzidis akyrtzi at gmail.com
Thu Dec 11 01:25:21 PST 2008


Talin wrote:
> Been having a bit of a problem with dyn_cast: Suppose I have a class A 
> that inherits from two base classes, both of which support dyn_cast. In 
> order to use dyn_cast on A, I need to do a bunch of extra work:
>
> 1) Since dyn_cast uses reinterpret_cast rather than static_cast, the 
> pointer value won't get adjusted by the cast operation, making the 
> pointer invalid. I end up having to redefine "cast_convert_val" and 
> other parts of the casting machinery for my type, so that it uses 
> static_cast.
>
> 2) In every class B which derives from A, it seems like I have to have 4 
> overloads of 'classof': One for B, one for A, and one for each of A's 
> top-most ancestors. Otherwise I get ambiguity errors.
>
> What I am wondering is, is this use case supported? And could it be made 
> easier?
>   

There is a use case in clang, take a look at this source file: 
http://llvm.org/svn/llvm-project/cfe/trunk/include/clang/AST/DeclBase.h
Contains the Decl class and DeclContext class and has "isa_impl_wrap" 
and "cast_convert_val" specializations.
Classes can inherit from both Decl and DeclContext, Decl is the "main" 
base class.
Subclasses that also inherit from DeclContext need to have two more 
methods:   castToDeclContext/castFromDeclContext, like this:

  static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
    return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
  }
  static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
    return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
  }


It's a fuss to setup and use multiple inheritance with dyn_cast, if you 
can simplify things let us know.


-Argiris



More information about the llvm-dev mailing list