Using Type Traits with Template Specialization
Can I use type traits to conditionally specialize a class template based on the properties of the template type?
Yes, you can use type traits to conditionally specialize a class template based on the properties of the template type. This is known as partial template specialization. Here's an example:
#include <iostream>
#include <type_traits>
template <typename T, typename Enable = void>
class MyClass {
public:
void print() {
std::cout << "General case\n";
}
};
template <typename T>
class MyClass<T, std::enable_if_t<
std::is_integral_v<T>>> {
public:
void print() {
std::cout << "Specialization for"
" integral types\n";
}
};
template <typename T>
class MyClass<T, std::enable_if_t<
std::is_floating_point_v<T>>> {
public:
void print() {
std::cout << "Specialization for"
" floating-point types\n";
}
};
int main() {
MyClass<void> generalObj;
generalObj.print();
MyClass<int> intObj;
intObj.print();
MyClass<double> doubleObj;
doubleObj.print();
}
General case
Specialization for integral types
Specialization for floating-point types
In this example, we have a class template MyClass
with two template parameters: T
and Enable
. The Enable
parameter defaults to void
and is used for enabling partial specialization based on type traits.
We define three different specializations of MyClass
:
- The general case: This is the default specialization that is used when no other specialization matches. It prints "General case".
- Specialization for integral types: This specialization is enabled when
T
is an integral type, usingstd::enable_if_t
andstd::is_integral_v
. It prints "Specialization for integral types". - Specialization for floating-point types: This specialization is enabled when
T
is a floating-point type, usingstd::enable_if_t
andstd::is_floating_point_v
. It prints "Specialization for floating-point types".
When instantiating MyClass
with different types, the appropriate specialization is selected based on the type traits. In the example, MyClass<void>
uses the general case, MyClass<int>
uses the specialization for integral types, and MyClass<double>
uses the specialization for floating-point types.
By using type traits with partial template specialization, you can create class templates that adapt their behavior and implementation based on the properties of the template type. This allows for more fine-grained control and optimization based on the specific characteristics of the types used.
Type Traits: Compile-Time Type Analysis
Learn how to use type traits to perform compile-time type analysis, enable conditional compilation, and enforce type requirements in templates.