Writing Custom Traits
Build your own type traits.
Building Your Own Traits
When the standard library lacks the question you need, you can write a custom trait. A trait is simply a template that exposes ::value or ::type.
Primary Template + Specialization
The standard pattern: a primary template defaulting to false, plus a specialization that matches the type of interest and sets true.
#include <iostream>
#include <type_traits>
template <typename T>
struct is_ptr : std::false_type {};
template <typename T>
struct is_ptr<T*> : std::true_type {};
int main() {
std::cout << is_ptr<int>::value << "\n";
std::cout << is_ptr<int*>::value << "\n";
return 0;
}All lessons in this course
- Querying Types
- Transforming Types
- Conditional Logic
- Writing Custom Traits