C/C++ Arena

Step 4 of 6

Concepts

A plain template accepts any type and fails with a wall of errors deep inside if the type doesn't fit. Concepts (C++20) state the requirements up front:

#include <concepts>

template <std::integral T>
T gcd(T a, T b) { ... }       // only integer types allowed

gcd(12, 18);    // ok
gcd(1.5, 2.0);  // clear error: double doesn't satisfy integral

You can write your own with requires:

template <typename T>
concept HasSize = requires(T t) { t.size(); };

Your turn: write template <std::integral T> T gcd(T a, T b) using Euclid's algorithm: while b != 0, replace (a, b) with (b, a % b). The tests also check that calling it with a double is rejected.

Previous: std::string_view Next: Ranges