比较std :: function和lambda [英] Compare of std::function with lambda
本文介绍了比较std :: function和lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将std :: function与lambda进行比较?
How to compare of std::function with lambda?
#include <iostream>
#include <functional>
using namespace std;
int main()
{
using Type = void( float, int );
std::function<Type> a;
auto callback = []( float d, int r )
{
cout << d << " " << r << endl;
};
static_assert( std::is_same< Type , decltype( callback ) >::value, "Callbacks should be same!" );
a(15.7f, 15);
}
因为在lambda的第一个参数是int
的情况下-代码将以1个警告进行编译.如何保护代码?
Because in case of first parametr of lambda would be int
- code would compile with 1 warning. How to protect code?
推荐答案
callback
的类型不是简单的函数.没有捕获的lambda可以衰减为函数指针,但它不是函数指针.这是本地类的实例.
The type of the callback
is not a simple function. A lambda with no captures can decay to function pointer but it isn't a function pointer. It's an instance of a local class.
如果要确保lambda的特定函数类型,可以通过将衰减强制为函数指针类型来实现:
If you want to ensure a specific function type for a lambda, you can do that by forcing the decay to function pointer type:
#include <iostream>
#include <functional>
using namespace std;
int main()
{
using Type = void( float, int );
std::function<Type> a;
auto callback = []( float d, int r )
{
cout << d << " " << r << endl;
};
// Ensures desired type.
{
Type* const func_ptr = callback; (void) func_ptr;
}
a = callback;
a(15.7f, 15);
}
这篇关于比较std :: function和lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文