SFINAE Pattern in C++

Level 5517 keystrokes

SFINAE with enable_if removes an overload from consideration when its condition is false, so process() picks the integer version for 42 and the floating-point version for 3.14159. A string matches the ordinary non-template overload.

C++ code

// Valid only for integer T; otherwise substitution fails and this overload is ignored
1template<typename T, typename = enable_if_t<is_integral_v<T>>>
2void process(T value) {
// Prints the value and its double
3 cout << "Integer: " << value << " (doubled: " << value * 2 << ")" << endl;
4}
5
// For floating-point T; the extra typename = void makes its signature differ from the first template
6template<typename T, typename = enable_if_t<is_floating_point_v<T>>, typename = void>
7void process(T value) {
// fixed and setprecision(2) show 2 decimals (and stay set on cout)
8 cout << "Float: " << fixed << setprecision(2) << value << endl;
9}
10
// Ordinary overload for string
11void process(const string& value) {
// \" prints double quotes; size() is the number of characters
12 cout << "String: \"" << value << "\" (length: " << value.size() << ")" << endl;
13}
14
// int: prints "Integer: 42 (doubled: 84)"
15process(42);
// double: prints "Float: 3.14"
16process(3.14159);
// Prints "String: "hello" (length: 5)"
17process(string("hello"));

Output

Integer: 42 (doubled: 84)
Float: 3.14
String: "hello" (length: 5)
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.

  • <× 40
  • "× 18
  • (× 11
  • )× 11
  • _× 9
  • ;× 6
  • >× 6
  • :× 5
  • ,× 3
  • {× 3

More C++ examples at level 5

← C++ typing practice