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.
Learn how to use type traits to perform compile-time type analysis, enable conditional compilation, and enforce type requirements in templates.