Concepts in C++20

Using Concepts with Class Templates

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

Abstract art representing computer hardware

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.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved