将 std::bind 转换为 std::function?

To transform std::bind to std::function?

提问人:Torch 提问时间:11/4/2022 最后编辑:JeJoTorch 更新时间:11/4/2022 访问量:260

问:

请参阅下面的代码

queue<function<void()> > tasks;

void add_job(function<void(void*)> func, void* arg) {
    function<void()> f = bind(func, arg)();
    tasks.push( f );
}

func是我想添加到其中的函数 has 参数是 .tasksarg

我怎样才能使用它来绑定它的参数,以便它可以分配给 的对象?std::bindstd::function<void()>

C++ 11 C+ +-标准库 std-function stdbind

评论

0赞 gerum 11/4/2022
绑定函数后不要调用该函数。

答:

0赞 GAVD 11/4/2022 #1

只是绑定它,不要执行它。

function<void()> f = bind(func, arg);
tasks.push( f );

评论

0赞 Torch 11/4/2022
谢谢,我以为返回一个对象......哈哈bind(func, arg)()
3赞 JeJo 11/4/2022 #2

我怎样才能使用它来绑定它的参数,以便它可以分配给 的对象?std::bindfunction<void()>

std::bind 返回一个未指定的可调用对象,该对象可以直接存储在 中。因此,您只需要std::function

function<void()> f = bind(func, arg); // no need to invoke the callable object
tasks.push( f );

但是,我建议使用 lambdas(从 C++ 11 开始)而不是 std::bind

其次,拥有全局变量也不是一个好的做法。我会提出以下示例代码。让编译器推断传递函数的类型及其(可变)参数 (function-template)。

template<typename Callable, typename... Args>
void add_job(Callable&& func, Args const&... args)
{
    // statically local to the function
    static std::queue<std::function<void()>> tasks;
    // bind the arguments to the func and push to queue
    tasks.push([=] { return func(args...); });
}

void fun1(){}
void fun2(int){}

int main()
{
    add_job(&fun1);
    add_job(&fun2, 1);
    add_job([]{}); // passing lambdas are also possible
}

观看演示

评论

0赞 Torch 11/4/2022
你提供这些有用的技能真是太好了,我非常感谢你,谢谢!
3赞 bolov 11/4/2022
@Torch 你应该对你认为有用的答案投赞成票。此外,一旦时间需要通过,请接受解决您问题的答案(如果有的话)。
0赞 Jakob Stark 11/4/2022
您将如何弹出和处理推送到本地范围队列的任务?static
1赞 LernerCpp 11/4/2022
@JakobStark 这时我们需要封装队列的 struct/ 类。在示例中,它也可以通过函数返回,....std::queue<std::function<void()>> const& add_job(...