[英]C++ - binding function
我有一些(库API,所以我无法更改函数原型)函数,其编写方式如下:
void FreeContext(Context c);
现在,在我执行的某个时刻,我有Context* local_context;
变量,这也不是一个改变的主题。
我希望使用boost::bind
和FreeContext
函数,但我需要从局部变量Context*
检索Context
。
如果我按照以下方式编写代码,编译器会说它是“非法间接”:
boost::bind(::FreeContext, *_1);
我设法通过以下方式解决了这个问题:
template <typename T> T retranslate_parameter(T* t) {
return *t;
}
boost::bind(::FreeContext,
boost::bind(retranslate_parameter<Context>, _1));
但这个解决方案对我来说似乎并不好。 有关如何使用*_1
类的解决方法的任何想法。 也许写一个小lambda函数?
你可以使用Boost.Lambda,它为_n
重载了*
运算符。
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <algorithm>
#include <cstdio>
typedef int Context;
void FreeContext(Context c) {
printf("%d\n", c);
}
int main() {
using boost::lambda::bind;
using boost::lambda::_1;
Context x = 5;
Context y = 6;
Context* p[] = {&x, &y};
std::for_each(p, p+2, bind(FreeContext, *_1));
return 0;
}
使用Boost.Lambda或Boost.Phoenix在占位符上有一个有效的operator*
。
您还可以将Context
指针放在带有自定义删除器的shared_ptr
:
#include <memory> // shared_ptr
typedef int Context;
void FreeContext(Context c)
{
printf("%d\n", c);
}
int main()
{
Context x = 5;
Context* local_context = &x;
std::shared_ptr<Context> context(local_context,
[](Context* c) { FreeContext(*c); });
}
不确定这是否相关。 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.