I am new to c++11, I define a template to take a function as parameter,
template <typename T>
void print_for_each(vector<T> v, std::function<void (T)> func){
std::for_each(v.begin(), v.end(), func);
}
I tried to pass the following Lambda expression to print_for_each,
auto printElement = [](int y) {
std::cout << y << " ";
};
Then I received the compiler warn said,
error: no matching function for call to 'print_for_each'
Then I changed the template function to be,
std::function<void (int)> func)
This time works. My question is, can std::function takes template type T ?
Thanks for answering it ! : )
答案 0 :(得分:2)
Lambdas are not the same as std::function
s. The former are functors (function objects) in disguise, whereas the latter are a different beast. Even though a lambda is "decay"-able to a std::function
, in template type deduction the compiler does not perform implicit conversions. So in this case the compiler tries to match two objects of incompatible types, hence it fails.
You may wonder why the compiler does not perform such implicit conversions. That's because by performing type conversions on top of argument type deduction, one can arrive at lots of "paradoxical" situations, in which more than one incompatible type can be a candidate.
Possible solutions:
You can change the signature of your function to
template <typename T, typename F>
void print_for_each(vector<T> v, F&& func){
std::for_each(v.begin(), v.end(), func);
}
You can wrap the lambda in a std::function
and passing the latter to your function (see @Brian's comment)
You can "help" the compiler and explicitly specify the template type parameter
print_for_each<int>(v, func);
In this case there is no template type deduction going on, and the lambda is allowed to decay to a std::function
via an implicit conversion.
答案 1 :(得分:1)
std::for_each
不需要std::function
,只需要一个仿函数。
您的模板也应该这样做:
template< typename C, typename F >
void print_for_each( C& c, F f )
{
std::for_each( c.begin(), c.end(), f );
}