如何比较 std::function 和 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 个警告。如何保护代码?
的类型callback
不是一个简单的函数。没有捕获的 lambda 可以衰减为函数指针,但它不是函数指针。它是本地类的一个实例。
如果您想确保 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;
};
// Ensures desired type.
{
Type* const func_ptr = callback; (void) func_ptr;
}
a = callback;
a(15.7f, 15);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)