Concepts — named constraints on template parameters for clearer, more readable code.
1#include <concepts>23// Define a concept4template<typename T>5concept Numeric = std::is_arithmetic_v<T>;67// Use concept as constraint8template<Numeric T>9T add(T a, T b) {10 return a + b;11}1213// Shorthand syntax14auto multiply(Numeric auto a, Numeric auto b) {15 return a * b;16}1718add(1, 2); // OK19add(1.5, 2.5); // OK20// add("a", "b"); // Error — constraint not satisfied2122// Requires expression23template<typename T>24concept Streamable = requires(T t) {25 { std::cout << t } -> std::same_as<std::ostream&>;26};
Benefits over SFINAE: