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.
The corresponding output appears below.
Here are some important observations:
- Primitive types such as int and double do not participate in Base/Derived relationship
- A class is a base of itself
- A class is considered a valid base class irrespective of whether the derivation is private, protected or public
- 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!
Recent Comments