Home >Backend Development >C++ >Why Doesn't C 11 Deduce Types When Using Lambda Functions with Function Templates?
When using C 11 templates or lambda functions, it is important to understand how type deduction works. In cases where you define a function template that accepts a std::function or lambda function, the compiler may not be able to automatically deduce the template type.
For example, consider the following function:
template<class A> set<A> filter(const set<A>& input, function<bool(A)> compare) { set<A> ret; for(auto it = input.begin(); it != input.end(); it++) { if(compare(*it)) { ret.insert(*it); } } return ret; }
If you try to call this function directly with a lambda function, you may encounter an error. This is because the compiler cannot deduce the template type from the lambda function alone:
set<int> myNewSet = filter(mySet,[](int i) { return i%2==0; });
This error can be avoided by explicitly specifying the template type:
set<int> myNewSet = filter<int>(mySet,[](int i) { return i%2==0; });
Alternatively, you can convert the lambda function to a std::function object:
std::function<bool(int)> func = [](int i) { return i%2 ==0; }; set<int> myNewSet = filter(mySet,func);
In cases where you need to filter a set of values based on a comparison function, you can provide a more generic solution by creating a function template that accepts a CompareFunction type:
template<class Value,class CompareFunction> set<Value> filter(const set<Value>& input,CompareFunction compare) { set<Value> ret; for(auto it = input.begin(); it != input.end(); it++) { if(compare(*it)) { ret.insert(*it); } } return ret; }
The above is the detailed content of Why Doesn't C 11 Deduce Types When Using Lambda Functions with Function Templates?. For more information, please follow other related articles on the PHP Chinese website!