Type Traits

Compile-time type information

Interview Relevant: Template utilities

Type Traits

Query and transform types at compile time.

Code Examples

Type traits for compile-time introspection.

cpp
1#include <type_traits>
2
3// Type queries
4is_integral<int>::value;           // true
5is_floating_point<double>::value;  // true
6is_pointer<int*>::value;           // true
7is_class<string>::value;           // true
8is_same<int, int32_t>::value;      // true (usually)
9
10// C++17 variable templates (shorter)
11is_integral_v<int>;  // true
12
13// Type transformations
14remove_const<const int>::type;     // int
15remove_reference<int&>::type;      // int
16add_pointer<int>::type;            // int*
17decay<int[10]>::type;              // int*
18common_type<int, double>::type;    // double
19
20// Conditional type
21conditional<true, int, double>::type;   // int
22conditional<false, int, double>::type;  // double
23
24// Use in templates
25template<typename T>
26void process(T value) {
27    using CleanType = remove_cv_t<remove_reference_t<T>>;
28    // Work with CleanType...
29}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In