Lambda函数作为参数传递 [英] Lambda function passed as parameter
问题描述
我有以下函数:
template< typename Range>
范围FindFirstIf(Range rng,bool(* Function)(typename Range :: ConstReference value))
对此函数,我试图传递一个lambda函数,像这样:
rng = FindFirstIf(rng,[] (const float& val){return(v <0.0f);});
其中 rng
是浮点列表的范围,因此 Range :: ConstReference
定义为 const float&
我的编译器(gcc)抱怨类型不匹配
C:\Programming\Collections\main.cpp | 24 |注意:不匹配的类型bool(*)(typename Range :: ConstReference)'和'main(int,char **)::& lambda(const float&)>'|任何人都可以告诉我我的代码有什么问题?
$ b < $ b 编辑:
当我传递这样的函数时,它的工作原理:
$ b b bool(* func)(const float& v)= [](const float& v){return v < 0.0f; };
当我尝试使用auto关键字时,它是一样的问题:
auto func = [](const float& v){return v< 0.0f; };
解决方案我怀疑你有一个类型o
如果您的示例是:
$ b $ [](const float& val){return(val< 0.0f); }
(v-> val)
和如果 Range :: ConstReference
是一个 const float&
legal C ++ 11。
这里棘手的部分是一些 lambdas会隐式转换为函数指针。也就是说,没有捕获的那些lambda将转换为具有相同签名的函数指针。
这是:
模板< class Range>
Range
FindFirstIf(Range,bool(* Function)(typename Range :: ConstReference value));
struct range
{
使用ConstReference = const float& amp;
};
int
main()
{
range rng;
rng = FindFirstIf(rng,[](const float& val){return(val< 0.0f);});
}
为我编译。
有了一个在网上gcc编译器,这似乎是一个bug在gcc 4.8,固定在4.9。
I have the following function:
template <typename Range>
Range FindFirstIf(Range rng, bool (*Function)(typename Range::ConstReference value))
To this function, I am trying to pass a lambda function like this:
rng = FindFirstIf(rng, [](const float& val) { return (v < 0.0f); });
Where rng
is Range of List of floats, so Range::ConstReference
is defined as const float&
My compiler (gcc) complains about type mismatch
C:\Programming\Collections\main.cpp|24|note: mismatched types 'bool (*)(typename Range::ConstReference)' and 'main(int, char**)::< lambda(const float&) >'|
Can anybody tell me what is wrong with my code?
Edit:
When I pass function like this, it works:
bool (*func)(const float& v) = [](const float& v) { return v < 0.0f; };
When I try to use auto keyword, it is same problem as before:
auto func = [](const float& v) { return v < 0.0f; };
解决方案 I suspect that either you have a type-o in your code, or you are using a version of gcc that does not completely implement lambdas (or possibly both).
If your example was:
[](const float& val) { return (val < 0.0f); }
(v -> val)
and if Range::ConstReference
is a const float&
, then the code is legal C++11.
The tricky part here is that some lambdas will implicitly convert to a function pointer. That is, those lambdas with no lambda-capture will convert to a function pointer with an identical signature.
This:
template <class Range>
Range
FindFirstIf(Range, bool (*Function)(typename Range::ConstReference value));
struct range
{
using ConstReference = const float&;
};
int
main()
{
range rng;
rng = FindFirstIf(rng, [](const float& val) { return (val < 0.0f); });
}
compiles for me.
With a little poking around with online gcc compilers, this appears to be a bug in gcc 4.8, fixed in 4.9.
这篇关于Lambda函数作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!