Concepts and Abbreviated Function Templates

How can I use concepts with abbreviated function templates?

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.

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.

Using Concepts with Class Templates
How can I use concepts to constrain the types allowed for a class template?
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?
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