仿函数 <- 函数指针 成员函数 std::bind

C++98

ptr_fun

函数指针 -> 仿函数

int sum ( int a , int b)
{
    return a+b;
}

auto sum_obj = std::ptr_fun(sum);

mem_fn

成员函数地址 -> 仿函数

class test {
    public :
        int sum(int a, int b){ return a+b ; }
};

auto sum_obj = std::mem_fn(&test::sum);

C++11

#include <functional>
#include <iostream>
class Test{
    public:
        Test( int i) : m_int(i) {}
        void Print() {
            std::cout<<m_int<<std::endl;     
        }

    private:        
        int m_int;
};

int main(){
    Test t1(1);
    Test t2(2);
    auto mem_fn = std::mem_fn(&Test::Print);
    auto fn = std::bind(&Test::Print, &t1);

    fn();
    mem_fn(t2);

    return 0;
}

你可能感兴趣的:(C++)