C++ Language/Templates/Concepts

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Traditionally, a templated-function like template<typename T> T Add(T x, T y) { return x + y; } will allow substitution using any type (even types like T=std::string that actually shouldn't be "added together").

You can define a "concept", which is a logical criteria that only some types might satisfy: template<typename T> concept IS_ADDABLE = std::is_arithmetic<T>::value;. Then we can limit allowed substitutions: template<typename T> requires IS_ADDABLE<T> T Add(T x, T y) {...}.

Additional information about "concepts"