1 auto类型推导

C++的隐式类型定义是在编译器推导, auto并不能代表实际的类型声明,只是一个类型声明的”占位符”。

在老的标准中已经有auto这个关键字了,不过一般都省略掉,它的含义是与static相对的。

2 std::function 和 std::bind

std::function 是一个类模板

#include
#include

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

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

/// 仿函数(函数对象)
class Bar
{
public:
    int operator()(int a)
    {
        std::cout << __FUNCTION__ << "(" << a << ")" << std::endl;
        return a;
    }
};

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

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

    Bar bar;
    fr2 = bar;
    std::cout << fr2(456) << std::endl;

    return 0;
}

std::function作为回调函数的例子

#include 
#include 

class A
{
    std::function callback_;

public:
    A(const std::function& f)
        : callback_(f)
        {
        }

    void notify(void)
    {
        callback_();
    }
};

class Foo
{
public:
    void operator()(void)
    {
        std::cout << __FUNCTION__ << std::endl;
    }
};

int main(void)
{
    Foo foo;
    A aa(foo);
    aa.notify();

    return 0;
}

std::function还可以作为函数入参

#include 
#include 

void call_when_even(int x, const std::function& f)
{
    if (!(x & 1))
    {
        f(x);
    }
}

void output(int x)
{
    std::cout << x << " ";
}

int main(void)
{
    for(int i = 0; i < 10; ++I)
    {
        call_when_even(i, output);
    }
    std::cout << std::endl;
    return 0;
}

总体来说就是替代函数指针的作用

3 lambda