std::function就是一个类模板,除了类函数之外,可以容纳所有的可调用对象。
可调用对象的定义:
1.函数指针
2.仿函数(operator)
3.可以被转化成函数指针的对象
4.类函数
#include <iostream>
#include <functional>
void Test_1(void)
{
std::cout << "Test_1" << std::endl;
}
class TestClass_1
{
public:
static int Test_2(int n)
{
std::cout << "Test_2 add 3 is " << n + 3 << std::endl;
return n;
}
};
class TestClass_2
{
public:
float operator()(float n)
{
std::cout << "operator add 5.6 is " << n + 5.6 << std::endl;
return n;
}
};
int main(int argc, char* argv[])
{
std::function<void(void)> Func_1 = Test_1;
Func_1();
std::function<int(int)> Func_2 = TestClass_1::Test_2;
std::cout << Func_2(5) << std::endl;
TestClass_2 This;
std::function<float(float)> Func_3 = This;
std::cout << Func_3(5.3f) << std::endl;
std::cin.get();
return 1;
}
std::function可以取代函数指针,可以作为回调函数使用,如下
#include <iostream>
#include <functional>
void ThreadFunction(int nValue,const std::function<void(int)>& fn)
{
if (nValue % 2)
{
fn(nValue);
}
}
void PrintNumber(int nValue)
{
std::cout << "Number is " << nValue << std::endl;
}
int main(int argc, char* argv[])
{
for (int i = 5; i < 20; i++)
ThreadFunction(i, PrintNumber);
std::cin.get();
return 1;
}