简单的bind实现

来源:互联网 发布:淘宝媒体公司招聘主播 编辑:程序博客网 时间:2024/06/06 04:31
#include "main.h"#include "iostream"#include <functional>using namespace std;namespace{class placeholder_{};placeholder_ _1;}template<typename R,typename T,typename arg>class simple_bind_t{private:typedef R(T::*F)(arg);F  f_;T* t_;arg& a_;public:simple_bind_t(F f, T* t, arg &a):f_(f), t_(t), a_(a){}R operator()(){return (t_->*f_)(a_);}};template <typename R,typename T,typename arg>class simple_bind_t2{private:typedef R(T::*F)(arg);F f_;T* t_;public:simple_bind_t2(F f, T*  t):f_(f), t_(t){}R operator()(arg &a){return (t_->*f_)(a);}};template <typename R,typename T,typename arg>simple_bind_t<R, T, arg> simple_bind1(R(T::*f)(arg), T *t, arg& a){return simple_bind_t<R, T, arg>(f, t, a);};template<typename R,typename T,typename arg>simple_bind_t2<R, T, arg> simple_bind(R(T::*f)(arg),T *t,placeholder_& a){return simple_bind_t2<R, T, arg>(f, t);};class bind_test{public:void print_string(const std::string str){printf("%s", str.c_str());}};void main(){bind_test t;std::string h = "hello\n";simple_bind1(&bind_test::print_string, &t, h)();simple_bind(&bind_test::print_string, &t, _1)(h);function< void(const std::string)> f;f = simple_bind(&bind_test::print_string, &t, _1);f(h);getchar();}


 

0 0