3

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

void FreeContext(Context c);

现在,在我执行的某个时刻,我有Context* local_context;变量,这也不是一个可以改变的主题。

我希望使用boost::bindwithFreeContext函数,但我需要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 函数?

4

3 回答 3

4

您可以使用 Boost.Lambda 重载*运算符 for _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;
}
于 2010-10-14T09:48:59.363 回答
2

使用 Boost.Lambda 或 Boost.Phoenix 来处理operator*占位符。

于 2010-10-14T09:49:36.963 回答
1

您还可以使用自定义删除器将Context指针放在 a中: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); });
}

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

于 2010-10-14T09:56:36.157 回答