How to check if one C++ class extends another (lik

2019-04-13 21:14发布

So generally having

class A { ... };
class B { ... };
class C: public A, public B {};  // C inherits from A and B.

when we create an instance of C and want to pass it into some function ho do we check if class we pass to a function is extending A?

2条回答
甜甜的少女心
2楼-- · 2019-04-13 21:34

C is defined as inheriting from A so there is no need to check:

It is mandatory that an instance of C is also a A (and a B).

However, if you have a function taking a A as a parameter, you can use dynamic_cast<> to check if the instance is actually a C:

void function(const A& a)
{
  const C* c = dynamic_cast<const C*>(&a);

  if (c)
  {
    // a is an instance of C and you can use c to call methods of C
  } else
  {
    // a is not an instance of C.
  }
}

For this to work, however, the base class type must be polymorphic (it must have at least a virtual method).

查看更多
SAY GOODBYE
3楼-- · 2019-04-13 21:44

The only time you'd need to do this is during compile time since implicit conversion works everywhere else. But if you want to see if some type T is a base of some type S then you can use SFINAE (or just use is_base_of<>):

template < typename T, typename S >
struct is_base_of // checks if T is a base of S
{
  typedef char (yes&) [1];
  typedef char (no&)  [2];

  void yes check(T*);
  void no  check(...);

  enum { value = sizeof(check(static_cast<S*>(0))) == sizeof(yes); }
};
查看更多
登录 后发表回答