孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
}

 

输出:

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

posted on 2021-10-11 20:51  孤独的猫  阅读(35)  评论(0编辑  收藏  举报