gpt4 book ai didi

c++ - std::bind 和 unique_ptr - 如何只移动?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:11:37 28 4
gpt4 key购买 nike

<分区>

我必须通过低级系统例程调用一个函数,该例程获取传递的函数和参数。

void doLater(void* func, void* arg);

我想使用绑定(bind)的任何函数和参数调用 callLater 函数。所以:

template<typename Call>
void caller(void *arg) {
std::unique_ptr<Call> upCall(static_cast<Call*>(arg));
(*upCall)();
}

template<class Function, class... Args>
void callLater(Function &&f, Args&&...args) {
typedef decltype(std::bind(std::forward<Function>(f), std::forward<Args>(args)...))) Call;
Call* call = new Call(std::bind(std::forward<Function>(f), std::forward<Args>(args)...));
doLater(caller<Call>, (void*) call);
}

将其与 std::unique_ptr 一起使用会导致不需要的拷贝,因此无法编译。

std::function<void(std::unique_ptr<int>)> foo = [](std::unique_ptr<int> i) {
std::cout << "Hello world!\n";
};
std::unique_ptr<int> value = std::make_unique<int>(1);

callLater(foo, std::move(value));

使用已删除函数 'std::unique_ptr<_Tp, _Dp>::unique_ptr...

一种可能的解决方法是使用 std::__bind_simple 就像它在 std::thread (gcc) 中使用的那样,但它不是标准化的。知道如何解决这个问题吗?

Live example.

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