是否可以使用 boost::bind 来有效地连接函数?
假设我有一个 boost::function ,具有名为 CallbackType 类型的任意签名。
- 是否可以使用
boost::bind
来编写一个函数,该函数采用与 CallbackType 相同的参数,但连续调用两个函子?
我对任何潜在的可能性持开放态度解决方案,但这里有一个...
...使用一些magic
模板的假设示例:
Template<typename CallbackType>
class MyClass
{
public:
CallbackType doBoth;
MyClass( CallbackType callback )
{
doBoth = bind( magic<CallbackType>,
protect( bind(&MyClass::alert, this) ),
protect( callback ) );
}
void alert()
{
cout << "It has been called\n";
}
};
void doIt( int a, int b, int c)
{
cout << "Doing it!" << a << b << c << "\n";
}
int main()
{
typedef boost::function<void (int, int, int)> CallbackType;
MyClass<CallbackType> object( boost::bind(doIt) );
object.doBoth();
return 0;
}
Assume that I have a boost::function of with an arbitrary signature called type CallbackType
.
- Is it possible to use
boost::bind
to compose a function that takes the same arguments as the CallbackType but calls the two functors in succession?
I'm open to any potential solution, but here's a...
...Hypothetical example using some magic
template:
Template<typename CallbackType>
class MyClass
{
public:
CallbackType doBoth;
MyClass( CallbackType callback )
{
doBoth = bind( magic<CallbackType>,
protect( bind(&MyClass::alert, this) ),
protect( callback ) );
}
void alert()
{
cout << "It has been called\n";
}
};
void doIt( int a, int b, int c)
{
cout << "Doing it!" << a << b << c << "\n";
}
int main()
{
typedef boost::function<void (int, int, int)> CallbackType;
MyClass<CallbackType> object( boost::bind(doIt) );
object.doBoth();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Boost 已经提供了一种创建一系列绑定函数的方法。使用 Lambda 的逗号运算符。
这将创建一个新的函子,
object
。当您使用三个参数调用该函子时,它将依次调用 mc.alert(),然后将这些参数传递给 doIt。括号很重要。为了使上面的示例正常工作,您需要将
alert
设为const
函数。如果它需要是非常量,则可以将指针传递给mc
,或者用boost::ref(mc)
。并且您需要使用 Boost.Lambda 的bind
而不是 Boost.Bind 的;后者与 Lambda 的函数组合运算符(尤其是逗号)不兼容。Boost already provides a way to create a sequence of bound functions. Use Lambda's comma operator.
That will create a new functor,
object
. When you invoke that functor with three arguments, it will in turn callmc.alert()
before passing those arguments todoIt
. The parentheses are important.For my example above to work, you'd need
alert
to be aconst
function. If it needs to be non-const, then either pass a pointer tomc
, or wrap it withboost::ref(mc)
. And you'll need to use Boost.Lambda'sbind
rather than Boost.Bind's; the latter isn't compatible with Lambda's function-combining operators (comma, in particular).Boost Bind 在其可变参数中使用了大量的预处理器黑客技术,不幸的是,我认为它没有提供用于头部修补的模式或工具,而这本质上就是这样。
Boost Bind uses a lot of preprocessor hacking for its variadic voodoo, and unfortunately I don't think it provides a pattern or tools for head-patching which is essentially what this is.