C – 绑定功能
发布时间:2020-12-16 09:30:25 所属栏目:百科 来源:网络整理
导读:我有一些(库API,所以我无法更改函数原型)函数,其编写方式如下: void FreeContext(Context c); 现在,在我执行的某个时刻,我有Context * local_context;变量,这也不是一个改变的主题. 我希望使用boost :: bind和FreeContext函数,但我需要从局部变量Context *
我有一些(库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("%dn",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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |