开发者

How to check if one C++ class extends another (like if that another one was an interface)?

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?


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).


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); }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜