std::is_base_of<>

Written by on April 26, 2020 in C++, Programming with 0 Comments

In our on-going series on C++ Type Traits, today’s topic is about the trait std::is_base_of<>.

For the official description, see this.

std::is_base_of<A, B>::value takes two arguments, both classes (or structs), and returns true if A is a base class of B and false otherwise. Trivially, std::<A, A>::value is true.

Let us look at an example covering various cases. For convenience, we will use the construct std::is_base_of_v<T1, T2> instead of std::is_base_of<T1, T2>::value.

Example Code

Example Code

The corresponding output appears below.

Output

Output

Here are some important observations:

  1. Primitive types such as int and double do not participate in Base/Derived relationship 
  2. A class is a base of itself
  3. A class is considered a valid base class irrespective of whether the derivation is private, protected or public
  4. Even if a class is included multiple times in a derived class via different paths (and hence could cause ambiguity), it is still a valid base class  

Notice that in line 39, we are using decltype to get the type of the variable qvar (it can be any expression).

As you can see, std::is_base_of<T1, T2> is a simple, but nevertheless useful, type trait in C++.

I used Visual Studio 2019 version 16.5.4 to test the above code. You can download the source from here.

Have a nice weekend!

Tags: , ,

Subscribe

If you enjoyed this article, subscribe now to receive more just like it.

Subscribe via RSS Feed

Leave a Reply

Your email address will not be published. Required fields are marked *

Top