使用boost :: function作为函数参数? [英] Use boost::function as function argument?

查看:116
本文介绍了使用boost :: function作为函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个函数foo并让它的行为不同。

(我正在采用策略或命令模式,它们看起来和我很相似。)



我的总体规划如下..首先,定义foo采取boost :: function type


  foo(boost :: function< someType> execFunction)
{
//做某事
execFunction参数);
//做某事
}


然后,根据我想要的,我给foo()不同的函数(作为参数)。



这会起作用吗?或者您会提出反对意见?

欢迎您发表评论。次要的相关问题是,
有时execFunction需要1个参数,而其他时间需要2个参数。

我可以在两种情况下使用boost :: function忽略不需要的第二个参数。

是否有更简单的方法来做到这一点?

解决方案

工作得很好。但有时最好使用
函子,这样你的调用者可以自由选择最适合他们的函数,并防止 boost :: function

 模板< typename Func> 
void foo(Func f){
f(myArgs);
}

您也可以为特定的增加添加一个重载

 模板<> 
void foo(const boost :: function< void(expectedtypes)>& f){
f(myArgs);
}

可能也会因为常量而重载。



对于接受不同元素的 boost :: function 对象的情况,我会使用重载。如果你走这条路线,就避免使用模板化版本,因为只要用户尝试使用函子(而不是 boost :: function )就会遇到麻烦不同的arity)。这个麻烦是可以解决的,但是会变得麻烦。您需要将呼叫发送到检测通话者身份并执行正确呼叫的事件。但正如你所说,模板是你的弱点,这不是真正的建议。


I want to call a function foo and let it behave differently.
(I'm adopting Strategy or Command pattern. They look similar to me.)

My overall plan is as follows..

First, define foo to take boost::function type

foo(boost::function<someType> execFunction)
{
// do something 
execFunction(args);
// do something
}

Then, I give foo() different functions(as argument) depending on what I want.

Would this work? or Would you advise against it?
Any comments are welcome.

edit

Minor related question is, sometimes execFunction needs 1 argument, and other times it needs 2 arguments.

I could use boost::function for both cases and just ignore the 2nd argument when not needed.
Is there a cleaner way to do this?

解决方案

This works very well. But sometimes it is preferable to work with a functor so your callers are free to choose what is best for them and to prevent the smalll overhead that comes with a boost::function:

template<typename Func>
void foo(Func f) {
  f(myArgs);
}

You can also add an overload for the specific boost::function to take the object by reference.

template<>
void foo(const boost::function<void (expectedtypes)>& f) {
  f(myArgs);
}

And possibly have that overloaded for constness as well.

For the case of accepting boost::function objects of different arity, I'd use overloading. If you go that route, avoid the templated version as you are going to run into trouble as soon as your users try to work with functors (as opposed to boost::function with different arity). This trouble is resolvable, but can get messy. You would need to dispatch the call to something that detects the arity of the funtor and executes the proper call. But as you said that templates are your weak-point, this isn't really recommended.

这篇关于使用boost :: function作为函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆