Constraining non-template member functions
Non-template functions that are members of class templates can be constrained in a similar way to what we have seen so far. This enables template classes to define member functions only for types that satisfy some requirements. In the following example, the equality operator is constrained:
template <typename T> struct wrapper { T value; bool operator==(std::string_view str) requires std::is_convertible_v<T, std::string_view> { return value == str; } };
The wrapper
class holds a value of a T
type and defines the operator==
member only for types that are convertible to std::string_view
. Let’s see how this can be used:
wrapper<int> a{ 42 }; wrapper<char const*> b{ "42" }; if(a == 42) {} // error if(b...