2010-10-14 121 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