C++ - 绑定(bind)函数

标签 c++ pointers function boost boost-bind

我有一些(库API,所以我不能改变函数原型(prototype))函数是这样写的:

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

最佳答案

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

关于C++ - 绑定(bind)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3931845/

相关文章:

c++ - 具有前向声明类型的 Boost.TypeErasure

c++ - VS2005 如何强制所有指针访问不对齐?

c++ - 2 [main] hw3 10368 cygwin_exception::open_stackdumpfile:将堆栈跟踪转储到 hw3.exe.stackdump

javascript - 尝试练习如何处理数组

javascript - 无法设置/读取未定义的属性

c++ - 为什么不能直接在stream中使用按位运算符?

c++ - 在 QLineEdit 中用点替换逗号

c++ - CLion 找不到 CMake 生成的 header ?

c++ - 为什么这个指针是8个字节?

Python 方法与函数