gpt4 book ai didi

C++ - 绑定(bind)函数

转载 作者:太空狗 更新时间:2023-10-29 20:18:27 24 4
gpt4 key购买 nike

我有一些(库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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com