Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...