Using Concepts with Class Templates

How can I use concepts to constrain the types allowed for a class template?

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.

Concepts in C++20

Learn how to use C++20 concepts to constrain template parameters, improve error messages, and enhance code readability.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Combining Concepts with Logical Operators
Can I combine multiple concepts using logical operators in a requires clause?
Using Type Traits in Requires Clauses
Can I use type traits in a requires clause to constrain template parameters?
Concepts and Abbreviated Function Templates
How can I use concepts with abbreviated function templates?
Using Trailing Requires Clauses
What are trailing requires clauses and when should I use them?
Benefits of Using Concepts
What are the main benefits of using concepts in C++20?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant