Function template in C++

Level 4172 keystrokes

Defines a function template maximum that returns the larger of two values of any comparable type, and calls it with int, double and char.

C++ code

// T is a type parameter, filled in by the compiler at each call
1template<typename T>
// Takes two values of the same type T and returns a T
2T maximum(T a, T b) {
// The ternary operator returns a if it is greater, otherwise b
3 return (a > b) ? a : b;
4}
5
// T is deduced as int: prints 20
6cout << maximum(10, 20) << endl;
// T is deduced as double: prints 3.5
7cout << maximum(3.5, 2.1) << endl;
// T is deduced as char; 'z' has the larger character code, so z is printed
8cout << maximum('a', 'z') << endl;

Output

20
3.5
z
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.

  • <× 13
  • (× 5
  • )× 5
  • ,× 4
  • ;× 4
  • '× 4
  • .× 2
  • >× 2
  • :× 1
  • ?× 1

More C++ examples at level 4

← C++ typing practice