Created
December 4, 2023 23:42
-
-
Save Gnomorian/5fc60ff35ea0c85e32472ad6a2241bb2 to your computer and use it in GitHub Desktop.
Using Concepts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// a blank struct to give an example of a failing concept | |
struct Something {}; | |
// a concept called Addable wich to satisfy requires that instances of T can use the + operator | |
template<typename T> | |
concept Addable = requires(T x) { x + x; }; | |
// a struct called Thing, which takes a type that is constrained by the 3 concepts after the 'requires' statement. | |
template<typename T> requires Addable<T> && std::copyable<T> && std::movable<T> | |
struct Thing | |
{ | |
T i {}; | |
}; | |
int wmain(int argc, wchar_t* args[]) | |
{ | |
Thing<int> i; // OK! int is Addable, Copyable and moveable. | |
Thing<Something> j; // error: | |
//message : see declaration of 'Thing' | |
//message: the concept 'Addable<Something>' evaluated to false | |
//message: binary '+' : 'Something' does not define this operator or a conversion to a type acceptable to the predefined operator | |
} | |
// requires statement: https://en.cppreference.com/w/cpp/language/constraints#Requires_clauses | |
// constraints and convepts: https://en.cppreference.com/w/cpp/language/constraints |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment