std::function

 

類模版std::function是一種通用、多態的函數封裝。
可調用對象的包裝器,它最重要的功能是實現延時調用。
std::function對象是對C++中現有的可調用實體的一種類型安全的封裝。

 

1、綁定普通函數
void func(void)
{
    std::cout << __FUNCTION__ << std::endl;
}

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

 

2、綁定一個類的靜態成員函數
class Foo
{
public:
    static int foo_func(int a)
    {
        std::cout << __FUNCTION__ << "(" << a << ") ->: ";
        return a;
    }
};
std::function<int(int)> fr2 = Foo::foo_func;
std::cout << fr2(123) << std::endl;

 

3、重載()函數
class Bar
{
public:
    int operator()(int a)
    {
        std::cout << __FUNCTION__ << "(" << a << ") ->: ";
        return a;
    }
};
Bar bar;
std::cout << bar(123) << std::endl;

 

4、回調函數
void call_when_even(int x, const std::function<void(int)>& f)
{
    if (!(x & 1))  //x % 2 == 0
    {
        f(x);
    }
}
void output(int x)
{
    std::cout << x << " ";
}
call_when_even(i, output);
本站公眾號
   歡迎關注本站公眾號,獲取更多信息