Concepts (C++)
Concepts in the C++ programming language are type constraints on templates (or generics).[src] Concepts are named Boolean predicates on template parameters, evaluated at compile time.[src] A concept may be associated with a template (class template, function template, member function of a class template, variable template, or alias template), in which case it serves as a constraint: it limits the set of arguments that are accepted as template parameters.[src] Originally dating back to suggestions for C++11, the original concepts specification has been revised multiple times before formally being standardised in C++20.[src]
Concepts in the C++ programming language are type constraints on templates (or generics).[src] Concepts are named Boolean predicates on template parameters, evaluated at compile time.[src] A concept may be associated with a template (class template, function template, member function of a class template, variable template, or alias template), in which case it serves as a constraint: it limits the set of arguments that are accepted as template parameters.[src] Originally dating back to suggestions for C++11, the original concepts specification has been revised multiple times before formally being standardised in C++20.[src] template requires Concept2 Concept3 auto myFunction(Concept4 auto param) requires Concept5 ; Concept1 : A type-constraint.[src] This kind replaces class or for declaring a template type parameter.[src] When using a concept instead of the former two the type is constraint.[src] Concept2 : A requires-clause.[src] Whenever a type-constraint does not work, for example, because the concept takes multiple parameters, a requires-clause can be used to apply more elaborated constraints.[src] Concept3 , Concept4 : A constrained placeholder type.[src] The same syntax is available for placeholder variable aka.[src] auto variable.[src] C++20 added abbreviated function templates which use auto as a placeholder type in the parameter declaration.[src] A constrained placeholder type allows to put constraints on the automatically deduced return type of a function or a variable.[src] Concept5 : A trailing requires-clause.[src] This form is similar to Concept2 with one notable exception.[src] A trailing requires-clause can be applied to a function in a class template.[src] This allows the function to remain a regular, template-free function, which can be enabled or disabled depending on the functions trailing requires-clause.[src] The constraint forms Concept1 and Concept2 can be used in all kinds of templates.[src] import std; using std::derived_from; using std::vector; class Player { // ...[src] }; // T is required to be a type whose inheritance upper bound is Player, // blocking any type that does not inherit from Player template T> void processListOfPlayers(const vector & players) { // ...[src] } This is similar to constrained generics in Java, and is equivalent to the following example: import java.util.List; class Player { // ...[src] } public class Example { // T is constrained to types that inherit from Player public static void processListOfPlayers(List players) { // ...[src] } } The following is a possible definition of the concept std::equality_comparable from the header of the C++ Standard Library.[src] This concept is satisfied by any type T such that for lvalues a and b of type T , the expressions a == b and a != b as well as the reverse b == a and b != a compile, and their results are convertible to a type that satisfies the concept "boolean-testable": /** * @namespace std * @brief The C++ Standard Library namespace */ namespace std { /** * @internal * @concept _WeaklyEqualityComparableWith * @brief The following concept is an implementation detail used to build equality_comparable * @tparam T the first template parameter to compare * @tparam U the second template parameter to compare */ template concept _WeaklyEqualityComparableWith = requires (const remove_reference & a, const remove_reference & b) { { a == b } -> same_as ; { a != b } -> same_as ; { b == a } -> same_as ; { b != a } -> same_as ; }; /** * @concept equality_comparable * @brief Checks that a == b, a != b, b == a, b != a compile and convert to bool * @tparam T the type to compare */ template concept equality_comparable = _WeaklyEqualityComparableWith ; } A function template constrained on this concept may be declared as follows: // constrained abbreviated function template declaration // using a constrained placeholder type (Concept4 from above) void f(const equality_comparable auto& x); or // constrained function template declaration // using a type constraint (Concept1 from above) template void f(const T& x); And may be called as usual: // OK, int satisfies equality_comparable f(42); C++ lacks type-safe variadic functions, like those of Java: void f(String...[src] args) , having only C-style , which lacks type safety.[src] However, C++ does feature variadic templates, allowing for an indefinite number of template parameters.[src] To constrain the parameter to be only of type T (similar to T...[src] args in Java), one can use the concept std::same_as or std::convertible_to (for types which may be intended to be convertible).[src] using std::same_as; // Equivalent to Java declaration // void fn(T...[src] args) template void fn(same_as auto...[src] args) { // ...[src] } This can be further constrained to any specific type: using std::convertible_to; using std::same_as; using std::string; // Equivalent to Java declaration // void foo(int...[src] args) void foo(same_as auto...[src] args) { // ...[src] } // Equivalent to Java declaration // void bar(String...[src] args) void bar(convertible_to auto...[src] args) { // ...[src] } import std; using std::same_as; using std::floating_point; template concept Drawable = requires (T t) { { t.draw() } -> same_as ; // T::draw must return void { t.area() } -> floating_point; // matches any floating-point type }; // The class Circle satisfies the Drawable concept // Circle does not need to declare it satisfies Drawable, however class Circle { private: const double radius; public: explicit Circle(double r): radius{r} {} void draw() const { // draw a circle...[src] } double area() const noexcept { return std::numbers::pi * radius * radius; } }; // Only types which satisfy Drawable may be used void render(const Drawable auto& shape) { // ...[src] shape.draw(); std::println("Drew shape with area {}", shape.area()); } Note that void render(const Drawable auto& shape); is equivalent to template void render(const T& shape); ; the former simply omits naming the template parameter.[src] This would be roughly similar to the following in Java: interface Drawable { void draw(); // must return void double area(); // must return double } // Circle must explicitly declare that it implements Drawable class Circle implements Drawable { private final double radius; public Circle(double r) { this.radius = r; } @Override public void draw() { // draw a circle...[src] } @Override public double area() { return Math.PI * radius * radius; } } // Only types which implement Drawable may be used static void render(Drawable shape) { // ...[src] shape.draw(); System.out.printf("Drew shape with area %f", shape.area()); } C++ concepts resemble Go interfaces very closely.[src] Unlike Java interfaces, Go interfaces do not require a type to declare that it implements the interface, as types implicitly satisfy the interface as long as it implements all of its requirements.[src] For example, this Drawable concept in C++ is roughly equivalent to the Go interface: import "math" type Drawable interface { Draw() Area() float64 } type Circle struct { radius float64 } func (c Circle) Draw() { // draw a circle...[src] } func (c Circle) Area() float64 { return math.Pi * c.radius * c.radius } using std::list; // std::list is typically a doubly-linked list, whose iterators are not random-access list l = {2, 1, 3}; std::sort(l.begin(), l.end()); Typical compiler diagnostic without concepts is over 50 lines of output, beginning with a failure to compile an expression that attempts to subtract two iterators: In instantiation of 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_List_iterator ; _Compare = __gnu_cxx::__ops::_Iter_less_iter]': error: no match for 'operator-' (operand types are 'std::_List_iterator ' and 'std::_List_iterator ') std::__lg(__last - __first) * 2, [..] If concepts are used, the error can be detected and reported in the context of the call: error: cannot call function 'void std::sort(_RAIter, _RAIter) [with _RAIter = std::_List_iterator ]' note: concept 'RandomAccessIterator()' was not satisfied auto x1 = f(y); // the type of x1 is deduced to whatever f returns Sortable auto x2 = f(y); // the type of x2 is deduced, but only compiles if it satisfies Sortable template concept_map ForwardIterator { typedef T value_type; }; concept TotalOrder { axiom Transitivity(Operator op, T x, T y, T z) { if (op(x, y) && op(y, z)) { op(x, z) true; } } } The original proposal was ultimately abandoned due to resolution ambiguity in compilation as well as increased complexity in compile-time behavior, while axioms could not be verified during compilation.[src] In contrast to this abandoned proposal, the C++20 version of Concepts is sometimes referred to as "Concepts Lite".[src] During the C++ standards committee meeting in March 2016, the evolution working group moved to merge Concepts into the mainline C++17 standard, but the motion was defeated in full committee.[src] Concepts v1 was merged into the C++20 draft.[src] Because C++ concepts were designed to mirror named requirements in C++, they were originally given PascalCase naming conventions within namespace std , however this was later changed to snake_case.[src] "The One Range" version of Range feature that depend on concepts was also merged into C++20.[src] using System; public class MyGenericClass where T : IComparable , allows ref struct where U : class, notnull, new() { // ...[src] } Java has wildcard generics, which are not as expressive as concepts but can represent bounds on types.[src] import java.util.List; import java.util.stream.Collectors; public static > List copyWhenGreater(List list, T threshold) { return list.stream() .filter(item -> item.compareTo(threshold) > 0) .map(T::toString) .collect(Collectors.toList()); } Kotlin, does not support Java-style type wildcards.[src] However, it represents ?[src] instead represented as * (for example, List ).[src] It otherwise has C#-style where clauses: fun copyWhenGreater(list: List , threshold: T): List where T : CharSequence, T : Comparable { return list.filter { it > threshold }.map { it.toString() } } Rust also uses where clauses to bound traits.[src] use std::cmp::Ord; struct MyStruct where T: Ord + Default, { value: T, } impl MyStruct where T: Ord + Default, { fn new(value: T) -> Self { MyStruct { value } } fn is_less_than(&self, other: &Self) -> bool { self.value[src]
63 sentences · 63 cited inline · 0 references stored
References
No reference rows published for this article.
Cite this article
MLA
"Concepts (C++)." encyclopegia.org, 2026, https://encyclopegia.org/wiki/concepts-c. Accessed 30 November 2026.
Chicago
"Concepts (C++)." encyclopegia.org. Accessed November 30, 2026. https://encyclopegia.org/wiki/concepts-c.
APA
encyclopegia.org. (2026). Concepts (C++). Retrieved November 30, 2026, from https://encyclopegia.org/wiki/concepts-c
Accessed November 30, 2026 · CC BY-SA 4.0 · citation page · JSON