Codectionary / Developer documentation / C++

C++20 constrained templates

C++20 concepts state requirements on template arguments. A constrained function can reject unsupported types during overload resolution and communicate its intended input domain.

Syntax

template<std::integral T> T twice(T value);

Examples

C++20 constrained templates

Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.

#include <concepts>
#include <iostream>
template<std::integral T>
T twice(T value) { return value + value; }
int main() {
    std::cout << twice(21) << '\n';
    // twice(2.5); // rejected: double does not satisfy integral
}
  1. Output: 42. Uncommenting the final call produces a constraint failure at compile time.

Best practices

  • Constrain the operations or semantic category you actually require. A valid type constraint does not prevent runtime overflow.

Runtime & versions

Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ISO C++ resources

Specifications & further reading