std::function是一个类末班,容纳除了类成员指针之外的所有可调用对象。

示例如下:

#include <iostream>
#include <functional>

void func(void)
{
std::cout << __FUNCTION__ << std::endl;
}

class Foo
{
public:
static int foo_func(int a)
{
std::cout << __FUNCTION__ << "(" << a << ") ->: ";
return a;
}
};

class Bar
{
public:
int operator()(int a)
{
std::cout << __FUNCTION__ << "(" << a << ") ->: ";
return a;
}
};

int main(void)
{
std::function<void(void)> fr1 = func;
fr1();

std::function<int(int)> fr2 = Foo::foo_func;
std::cout << fr2(123) << std::endl;

Bar bar;
fr2 = bar;
std::cout << fr2(123) << std::endl;
//system("pause");
return 0;
}

 

输出:

可调用对象包装器std::function_c#

 类似于C#的委托,指向函数的模板