October 21th Wednesday

  I  learnt how to impelement a simple functional object in C++.

 

template <typename R, typename Arg> class invoker_base {
public:
  virtual R operator()(Arg arg)=0;
};

 

template <typename R, typename Arg> class function_ptr_invoker 
: public invoker_base<R,Arg> {
R (*func_)(Arg);
public:
function_ptr_invoker(R (*func)(Arg)):func_(func) {}

R operator()(Arg arg) {
return (func_)(arg);
}
};

template <typename R, typename Arg, typename T>
class member_ptr_invoker :
public invoker_base<R,Arg> {
R (T::*func_)(Arg);
T* t_;
public:
member_ptr_invoker(R (T::*func)(Arg),T* t)
:func_(func),t_(t) {}

R operator()(Arg arg) {
return (t_->*func_)(arg);
}
};
template <typename R, typename Arg, typename T> 
class function_object_invoker :
public invoker_base<R,Arg> {
T t_;
public:
function_object_invoker(T t):t_(t) {}

R operator()(Arg arg) {
return t_(arg);
}
};
template <typename R, typename Arg> class function1 {
invoker_base<R,Arg>* invoker_;
public:
function1(R (*func)(Arg)) :
invoker_(new function_ptr_invoker<R,Arg>(func)) {}

template <typename T> function1(R (T::*func)(Arg),T* p) :
invoker_(new member_ptr_invoker<R,Arg,T>(func,p)) {}

template <typename T> function1(T t) :
invoker_(new function_object_invoker<R,Arg,T>(t)) {}

R operator()(Arg arg) {
return (*invoker_)(arg);
}

~function1() {
delete invoker_;
}
};
  OK.  let's try it.
bool some_function(const std::string& s) {
std::cout << s << " This is really neat/n";
return true;
}

class some_class {
public:
bool some_function(const std::string& s) {
std::cout << s << " This is also quite nice/n";
return true;
}
};

class some_function_object {
public:
bool operator()(const std::string& s) {
std::cout << s <<
" This should work, too, in a flexible solution/n";
return true;
}
};
int main() {
function1<bool,const std::string&> f1(&some_function);
f1(std::string("Hello"));

some_class s;
function1<bool,const std::string&>
f2(&some_class::some_function,&s);

f2(std::string("Hello"));

function1<bool,const std::string&>
f3(boost::bind(&some_class::some_function,&s,_1));

f3(std::string("Hello"));

some_function_object fso;
function1<bool,const std::string&>
f4(fso);
f4(std::string("Hello"));
}
  The example is from the boost library.  ^_^
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值