C++20 Concepts & Type Constraints (requires)

🔴 Advanced

📖 Definition

Introduced in ISO C++20, Concepts (in <concepts>) constrain template arguments at compile time (e.g. template<std::integral T>), replacing SFINAE with clean, readable compiler diagnostics.

💡 Code Example (C++20)

#include <iostream>
#include <concepts>

template <std::integral T>
T addInts(T a, T b) {
    return a + b;
}

int main() {
    std::cout << "Sum: " << addInts(10, 20) << "\n"; // Compiles cleanly
    // addInts(3.14, 2.71); // COMPILATION ERROR: double fails std::integral concept!
    return 0;
}