Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

rtti - C++: using typeinfo to test class inheritance

I have a pointer to a polymorphic type, p. I also have a type_info for a class somewhere in the same hierarchy, ti.

If I just compare the typeid(*p) == ti, then I can test at runtime whether the pointer is pointing to a direct instance of that class.

Is there a similar way to use C++'s RTTI to test whether *p inherits from that class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's no way to do this in standard C++ alone. If you're using an implementation that has the Itanium C++ ABI1 you can do this though, for example:

#include <iostream>
#include <typeinfo>
#include <cxxabi.h>
#include <memory>

class base {
protected:
  base() {
  }
public:
  static bool check(const std::type_info& p) {
    // Find the real type_info for single inheritance non virtual 
    const __cxxabiv1::__si_class_type_info* test = dynamic_cast<const __cxxabiv1::__si_class_type_info*>(&p);
    return test ? typeid(base) == *test->__base_type : false;
  }

  virtual ~base() {}
};

class der : public base {
};

class foo {};

int main() {
  der d;
  foo f;

  std::cout << base::check(typeid(d)) << "
";
  std::cout << base::check(typeid(f)) << "
";
}

Here this works because the type has a single, non-virtuallly inherited base. You can support more cases though with care and similar dynamic_casts.

Whilst this is possible under these certain circumstances I think you're solving the wrong problem though - a solution based around a std::map is more portable and avoids relying on implementation details like this.

1 confusingly named, it's a surprisingly large compiler/architecture list, not just Itanium


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...