[英]No matching function call error with usage of, lambda expressions and std::function.
I am trying to use this lambda expression in my code. 我试图在我的代码中使用此lambda表达式。 And looks like something's wrong with definition of functor or lambda.
似乎函子或lambda的定义有问题。
I believe the lambda expression is true. 我相信lambda表达式是正确的。 but I can't satisfy the prototype of function I defined.
但是我不能满足我定义的函数原型。
Function definition: 功能定义:
template<typename E, typename container>
void for_each(Iterator<E,container> begin, std::function<void(E&)> fun)
{
do // does the given unary functor to elements
{ //from starting iterator 'til the end.
fun(*begin);
begin = begin.next();
}while(begin.hasNext());
fun(*begin);
}
And caller: 和来电者:
for_each(c.iterator(), [&](E& e){add(e);});
I except achieve this function call with lambda expression. 除了用lambda表达式实现此函数调用之外,我没有。 But compiler says "error: no matching function for call to .."
但是编译器说“错误:没有匹配的函数来调用..”
lambda is not std::function
, so deduction fails. lambda不是
std::function
,所以推导失败。
You might simply pass generic Functor
: 您可以简单地通过泛型
Functor
:
template<typename E, typename container, typename F>
void for_each(Iterator<E, container> begin, F&& fun)
{
// ...
}
Issues with the code and Possible solution approaches below: 下面的代码和可能的解决方法问题:
1. A Lambda expression
is not std::function
, it can only be stored in an object of type std::function
. 1.
Lambda expression
不是std::function
,只能存储在std::function
类型的对象中。
Approach: (With your existing signature): 方法:(使用您现有的签名):
std::function<void()> f = []() -> void { // do something };
for_each(vec.begin(), vec.end(), f);
2. Better solution would be to use a Callable
as a parameter (Go to end of the answer). 2.更好的解决方案是将
Callable
用作参数(转到答案的结尾)。
3. If you want to pull up your own version of for_each
, why not follow the implementation that is consistent with other algorithms or for that matter with the implementation of for_each
in the algorithm header. 3.如果要提取自己的
for_each
版本,为什么不遵循与其他算法一致的实现,或者不遵循算法标头中for_each
的实现。
Does all you want and is also consistent with other standard algorithms: en.cppreference.com/algorithms/for_each : 是否满足您的所有需求,并且与其他标准算法一致: en.cppreference.com/algorithms/for_each :
template<class InputIt, class UnaryFunction>
constexpr UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f)
{
for (; first != last; ++first) {
f(*first);
}
return f;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.