Type Traits: Compile-Time Type Analysis

Using std::is_base_of with Template Types

How can I use std::is_base_of to check if a template type is derived from a specific base class?

Illustration representing computer hardware

To use std::is_base_of with a template type, you can pass the base class and the template type as the template arguments to std::is_base_of. Here's an example:

#include <iostream>
#include <type_traits>

class BaseClass {};
class DerivedClass : public BaseClass {};

template <typename T>
void checkDerived() {
  if constexpr (std::is_base_of_v<BaseClass, T>) {
    std::cout << "T is derived from BaseClass\n";
  } else {
    std::cout << "T is not derived from BaseClass";
  }
}

int main() {
  // Output: T is derived from BaseClass
  checkDerived<DerivedClass>();

  // Output: T is not derived from BaseClass
  checkDerived<int>();
}
T is derived from BaseClass
T is not derived from BaseClass

In this example, the checkDerived function uses std::is_base_of_v to check if the template type T is derived from BaseClass. The if constexpr statement allows conditional compilation based on the result of the type trait.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved