You can use concepts to constrain the types allowed for a class template by placing the concept name before the typename in the template parameter list. Here's an example:
#include <concepts>
template <std::integral T>
class IntegralContainer {
public:
IntegralContainer(T val) : value(val) {}
T value;
};
int main() {
// Valid
IntegralContainer<int> intContainer(42);
// Invalid, double is not an integral type
IntegralContainer<double> doubleContainer(3.14);
}
error: 'IntegralContainer': the associated constraints are not satisfied
the concept 'std::integral<double>' evaluated to false
In this example, the IntegralContainer
class template is constrained to only accept integral types using the std::integral
concept. Attempting to instantiate the template with a non-integral type like double
will result in a compilation error.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to use C++20 concepts to constrain template parameters, improve error messages, and enhance code readability.