代码之家  ›  专栏  ›  技术社区  ›  Yippie-Ki-Yay

C++绑定函数

  •  3
  • Yippie-Ki-Yay  · 技术社区  · 14 年前

    (库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函数?

    3 回复  |  直到 14 年前
        1
  •  4
  •   kennytm    14 年前

    * 操作员 _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;
    }
    
        2
  •  2
  •   usta    14 年前

    使用Boost.Lambda或Boost.Phoenix operator* 在占位符上。

        3
  •  1
  •   Daniel Lidström    14 年前

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

    但不确定这是否相关。祝你好运!