If Constexpr in C++

Level 5462 keystrokes

describe<T>() uses if constexpr with type traits to choose a description at compile time. Only the branch that matches T is compiled, so each instantiation simply returns one string.

C++ code

// T is given explicitly at the call, e.g. describe<int>()
1template<typename T>
2string describe() {
// Integer types (int, char, bool...); decided at compile time
3 if constexpr (is_integral_v<T>) {
4 return "integer type";
// Floating-point types: float, double, long double
5 } else if constexpr (is_floating_point_v<T>) {
6 return "floating point type";
// Pointer types such as int*
7 } else if constexpr (is_pointer_v<T>) {
8 return "pointer type";
// Everything else, e.g. string
9 } else {
10 return "other type";
11 }
12}
13
// Prints "int: integer type"
14cout << "int: " << describe<int>() << endl;
// Prints "double: floating point type"
15cout << "double: " << describe<double>() << endl;
// Prints "int*: pointer type"
16cout << "int*: " << describe<int*>() << endl;
// string is none of the above: prints "string: other type"
17cout << "string: " << describe<string>() << endl;

Output

int: integer type
double: floating point type
int*: pointer type
string: other type
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.

  • <× 32
  • "× 16
  • ;× 8
  • (× 8
  • )× 8
  • >× 8
  • _× 7
  • {× 5
  • }× 5
  • :× 4

More C++ examples at level 5

← C++ typing practice