【问题标题】:C++ - binding functionC++ - 绑定函数
【发布时间】:2010-10-14 09:35:01
【问题描述】:

我有一些(库API,所以我不能更改函数原型)函数,编写方式如下:

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

【问题讨论】:

    标签: c++ pointers function boost boost-bind


    【解决方案1】:

    您可以使用 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;
    }
    

    【讨论】:

      【解决方案2】:

      使用 Boost.Lambda 或 Boost.Phoenix 在占位符上设置有效的 operator*

      【讨论】:

        【解决方案3】:

        您还可以使用自定义删除器将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); });
        }
        

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

        【讨论】:

        • Lambda 表达式仅在 C++0x 中受支持。
        猜你喜欢
        • 2022-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-07
        相关资源
        最近更新 更多