Type Traits in C++

Level 5512 keystrokes

Type traits from <type_traits> answer questions about a type at compile time. analyze<T>() prints five of them for int, const double and int*; without boolalpha, true and false print as 1 and 0.

C++ code

// T is chosen at the call, e.g. analyze<int>()
1template<typename T>
2void analyze() {
3 cout << "Type info:" << endl;
// Each _v trait is a bool constant computed at compile time
4 cout << " is_integral: " << is_integral_v<T> << endl;
5 cout << " is_floating_point: " << is_floating_point_v<T> << endl;
6 cout << " is_pointer: " << is_pointer_v<T> << endl;
// is_const looks at the top-level const of T
7 cout << " is_const: " << is_const_v<T> << endl;
8 cout << " is_reference: " << is_reference_v<T> << endl;
9}
10
11cout << "=== int ===" << endl;
// int: only is_integral is 1
12analyze<int>();
13cout << "=== const double ===" << endl;
// const double: is_floating_point and is_const are 1
14analyze<const double>();
15cout << "=== int* ===" << endl;
// int*: only is_pointer is 1 (the pointer itself is not const)
16analyze<int*>();

Output

=== int ===
Type info:
  is_integral: 1
  is_floating_point: 0
  is_pointer: 0
  is_const: 0
  is_reference: 0
=== const double ===
Type info:
  is_integral: 0
  is_floating_point: 1
  is_pointer: 0
  is_const: 1
  is_reference: 0
=== int* ===
Type info:
  is_integral: 0
  is_floating_point: 0
  is_pointer: 1
  is_const: 0
  is_reference: 0
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 55
  • "× 18
  • =× 18
  • _× 17
  • ;× 12
  • >× 9
  • :× 6
  • (× 4
  • )× 4
  • *× 2

More C++ examples at level 5

← C++ typing practice