2012年4月22日 星期日

[C++] class member pointer usage

Use C++ member pointer for container.
#include <iostream>
#include <vector>
#include <map>
#include <functional>
                
class Foo       
{               
public:         
    Foo() {}    
    ~Foo() {}   
    int A(int a)
    {           
        return a+1;
    }             
    int B(int a)
    {           
        return a+2;
    }           
};              
                
int main()      
{               
    // use mem_fun_ref which can be used for for_each ... etc
    std::vector<std::mem_fun1_ref_t<int, Foo, int> > vec;   
    std::map<std::string, std::mem_fun1_ref_t<int, Foo, int> > map1;
    Foo a;      
    std::string s("aa");
                
    vec.push_back(std::mem_fun_ref(&Foo::A));
    map1.insert(std::pair<std::string, std::mem_fun1_ref_t<int, Foo, int> >(s, std::mem_fun_ref(&Foo::A)));
    std::cout << vec[0](a, 1) << std::endl;
    std::cout << map1.begin()->second(a, 2) << std::endl;   
                
    // use function pointer directly
    typedef int (Foo::*FuncPtr)(int);
    std::vector<FuncPtr> vec2;
    vec2.push_back(&Foo::A);
    vec2.push_back(&Foo::B);
    std::cout << (a.*(vec2[1]))(3) << std::endl; // it should be 5
                
    std::map<std::string, FuncPtr> map2;
    map2[s] = &Foo::B;
    std::cout < (a.*(map2[s]))(3) < std::endl; // it should be 5
    return 0;   
}