std::mem_ptr与std::mem_ptr_ref

std::mem_ptr与std::mem_ptr_ref都需要一个类的成员函数指针作为参数,然后返回一个包装对象。这个包装对象重载了operator(),该对象内部仅有一个成员:参数传进的一个成员函数的地址。

调用成员函数时还需要一个对象实例,这个实例就是在调用operator()会传进来的,对于std::mem_ptr的operator()的参数是对象指针,而对于std::mem_ptr_ref的operator()的参数是对象引用。


template<typename Result, typename Type>
class mem_fun_wrapper
{
public:
mem_fun_wrapper(Result (Type::*ptr_mem_fun)()) : _ptr_mem_fun(ptr_mem_fun)
{
}

Result operator()(Type *instance)
{
return (instance->*_ptr_mem_fun)();
}

private:
Result (Type::*_ptr_mem_fun)();
};

template<typename Result, typename Type>
mem_fun_wrapper<Result, Type> mem_fun(Result (Type::*ptr_mem_fun)())
{
return mem_fun_wrapper<Result, Type>(ptr_mem_fun);
}

class Test
{
public:
bool hello()
{
std::cout<<"hello world"<<std::endl;
return true;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
std::vector<Test*> vec;
vec.push_back(&Test());
vec.push_back(&Test());
vec.push_back(&Test());
std::for_each(vec.begin(), vec.end(), mem_fun(&Test::hello));
return 0;
}

posted @ 2013-01-05 19:56  avexer  阅读(185)  评论(0编辑  收藏  举报