Concepts in C++

Level 5461 keystrokes

C++20 concepts name requirements on template parameters: Numeric accepts integer and floating-point types, and Printable accepts any type that can be written to cout. Calls that break a requirement fail to compile with a clear error.

C++ code

1template<typename T>
// Numeric: satisfied by integer or floating-point types
2concept Numeric = is_integral_v<T> || is_floating_point_v<T>;
3
4template<typename T>
// requires lists expressions that must be valid for T
5concept Printable = requires(T t) {
// cout << t must compile and return ostream&
6 { cout << t } -> same_as<ostream&>;
7};
8
// Using the concept instead of typename restricts T to numeric types
9template<Numeric T>
// Returns x squared, with the same type as x
10T square(T x) { return x * x; }
11
// Accepts only types that satisfy Printable
12template<Printable T>
13void display(const T& value) {
14 cout << "Value: " << value << endl;
15}
16
// int: prints "Square of 5: 25"
17cout << "Square of 5: " << square(5) << endl;
// double: prints "Square of 2.5: 6.25" (square("a") would not compile)
18cout << "Square of 2.5: " << square(2.5) << endl;
// A string literal is printable: prints "Value: Hello Concepts"
19display("Hello Concepts");
// Prints "Value: 42"
20display(42);

Output

Square of 5: 25
Square of 2.5: 6.25
Value: Hello Concepts
Value: 42
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.

  • <× 27
  • ;× 9
  • "× 8
  • >× 8
  • (× 7
  • )× 7
  • _× 6
  • {× 4
  • }× 4
  • :× 3

More C++ examples at level 5

← C++ typing practice