C 11 Type Deduction Limitations with Lambda Functions
When working with lambda functions and std::function in C 11, type deduction may not be performed as expected, leading to errors.
The Issue
Consider the following function template:
template<class A> set<A> filter(const set<A>& input, function<bool(A)> compare);
When calling this function with a lambda function directly, for example:
filter(mySet, [](int i) { return i % 2 == 0; });
an error will occur due to the compiler's inability to infer the template type for A.
Explanation
Lamda functions, while providing convenient syntax for anonymous functions, are distinct types that implement the operator() method. They are not directly supported by type deduction, which expects exact types.
Solutions
Several workarounds exist to address this issue:
set<int> myNewSet = filter<int>(mySet, [](int i) { return i % 2 == 0; });
std::function<bool(int)> func = [](int i) { return i % 2 == 0; }; set<int> myNewSet = filter(mySet, func);
template<class A, class CompareFunction> set<A> filter(const set<A>& input, CompareFunction compare);
In this modified template, the type CompareFunction represents a function object that takes an A argument and returns a boolean. The template parameter is no longer deduced, but explicitly specified.
Additional Features
With the new decltype keyword and function return type syntax, the function can be further generalized to automatically determine the return type:
template<class Value, class CompareType, class IndexType> auto filter(const set<Value>& input, CompareType compare, IndexType index) -> map<decltype(index(*(input.begin()))), Value> { ... }
This template function expects three types: the input set value type, the comparison function type, and the index function type. The return type is automatically determined and instantiated.
The above is the detailed content of Why Does C 11 Type Deduction Fail with Lambdas in Function Templates?. For more information, please follow other related articles on the PHP Chinese website!