Concepts in C++20

Concepts and Abbreviated Function Templates

How can I use concepts with abbreviated function templates?

Abstract art representing computer hardware

You can use concepts with abbreviated function templates by placing the concept name before the auto keyword in the parameter declaration. This allows you to constrain the types deduced for the auto parameters. Here's an example:

#include <concepts>
#include <iostream>

void printIntegral(std::integral auto value) {
  std::cout << "Integral value: " << value;
}

int main() {
  // Valid, int is an integral type
  printIntegral(42);

  // Invalid, double is not an integral type
  printIntegral(3.14);
}
error: 'printIntegral': no matching overloaded function found
could be 'void printIntegral(_T0)'
the associated constraints are not satisfied
the concept 'std::integral<double>' evaluated to false
the constraint was not satisfied

In this example, the printIntegral function is an abbreviated function template that accepts a single parameter of an integral type. The std::integral concept is used before the auto keyword to constrain the deduced type.

Calling the function with an integral argument like 42 is valid, but calling it with a non-integral argument like 3.14 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