Constraining class templates
Class templates and class template specializations can also be constrained just like function templates. To start, we’ll consider the wrapper
class template again, but this time with the requirement that it should only work for template arguments of integral types. This can be simply specified in C++20 as follows:
template <std::integral T> struct wrapper { T value; }; wrapper<int> a{ 42 }; // OK wrapper<double> b{ 42.0 }; // error
Instantiating the template for the int
type is fine but does not work for double
because this is not an integral type.
Requirements that also be specified with requires clauses and class template specializations can also be constrained. To demonstrate this, let’s consider the scenario when we want to specialize the wrapper
class template but only for types whose size is 4
bytes. This can be implemented as follows...