Concepts
Concepts are named sets of template parameter requirements. They are evaluated at compile time and are used during overload resolution to select the most appropriate function overload; that is, they are used to determine which function template will be instantiated and compiled.
We will create a concept for arithmetic types and use it in our add template function, as follows:
template<typename T>
concept Arithmetic = std::is_arithmetic_v<T>;
template<Arithmetic T>
T add(T a, T b) {
T result = a + b;
if constexpr (std::is_integral_v<T>) {
printf("%d + %d = %d\r\n", a, b, result);
} else if constexpr (std::is_floating_point_v<T>) {
printf("%.2f + %.2f = %.2f\r\n", a, b, result);
}
return a + b;
}
In the preceding code, we created the Arithmetic concept and used it in the add function template to put requirements on the T template type. The add template function is now easier to...