...

/

Constraining Nontemplate Member Functions

Constraining Nontemplate Member Functions

Learn about constraining nontemplate member functions in C++20.

Understanding nontemplate member functions

Nontemplate 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;
}
};
Constraining the equality operator of the wrapper class template

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:

Press + to interact
wrapper<int> a{ 42 };
wrapper<char const*> b{ "42" };
// if(a == 42) {} // error
if(b == "42") {} // OK

Note: Uncommenting line 3 in the code above will generate an error.

We have two instantiations of the ...