C 11 Type Deduction Limitations with Lambda Functions
C 11 allows for template type deduction, but there are limitations when lambda functions or std::function are involved. When using functions with template parameters, the compiler can often deduce the template type from the argument types. However, this deduction fails when using lambdas directly in the argument.
Problem Statement
The following code fails to deduce the template type for the function filter():
template<class A> set<A> filter(const set<A>& input, function<bool(A)> compare) { // ... }
When calling this function directly with a lambda function as the compare argument, the compiler raises an error:
filter(mySet, [](int i) { return i % 2 == 0; }); // Throws an error
Reason for the Error
The root cause of this error lies in the nature of lambda functions. While they behave like function objects, they are not true functions. Lambda functions are not converted implicitly to std::function objects, which would allow the compiler to deduce the type.
Workarounds
Several workarounds exist to resolve the deduction issue:
1. Explicit Template Argument:
Specify the template argument explicitly:
filter<int>(mySet, [](int i) { return i % 2 == 0; });
2. Create an std::function Object:
Convert the lambda function to an std::function object and pass it as a parameter:
std::function<bool(int)> compare = [](int i) { return i % 2 == 0; }; filter(mySet, compare);
3. Use Alternative Function Definition:
Redefine the filter() function to accept a general comparison function object:
template<class Value, class CompareType> set<Value> filter(const set<Value>& input, CompareType compare) { // ... }
Now, the function can be called with a lambda function directly:
filter(mySet, [](int i) { return i % 2 == 0; });
Conclusion
Lambda functions provide a convenient way to define short-lived functions, but they can introduce complexity regarding template type deduction. By understanding the limitations and using the appropriate workarounds, developers can effectively leverage lambdas in C 11 code.
The above is the detailed content of Why Does C 11 Template Type Deduction Fail with Lambda Functions in `filter()`?. For more information, please follow other related articles on the PHP Chinese website!