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.
Learn how to use C++20 concepts to constrain template parameters, improve error messages, and enhance code readability.