2010-10-14 101 views
3

我有一些(库API,所以我不能改变的函数原型),这是写了下面的方法功能:现在C++ - 结合功能

void FreeContext(Context c); 

,在我执行我的一些时刻有Context* local_context;变量,这也是不改变。

我希望用boost::bindFreeContext功能,但我需要从本地变量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函数?

+1

你有没有试过Boost.Lambda? – kennytm 2010-10-14 09:40:22

回答

4

您可以使用已为_n重载*运算符的Boost.Lambda。

#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; 
} 
2

二者必选其一Boost.Lambda或Boost.Phoenix有一个占位符的工作operator*

1

您也可以放置在shared_ptrContext指针与定制删除:

#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); }); 
} 

不知道这是相关的,但。祝你好运!

+1

仅在C++ 0x中支持Lambda表达式。 – kennytm 2010-10-14 10:33:22

+0

@ KennyTM:肯尼,没错。 – 2010-10-14 11:47:49