假装packaged_task是可复制的

Pretending packaged_task is copy constructable

本文关键字:可复制 task packaged 假装      更新时间:2023-10-16

我一直在寻找解决方法来解决使用 std::function 擦除std::packaged_task的问题。

我想做的是这样的:

#include <future>
#include <functional>
#include <iostream>
namespace {
  std::function<void()> task;
  std::future<int> make(int val) {
    auto test = std::packaged_task<int()>([val](){
      return val;
    });
    auto fut = test.get_future();
    task = std::move(test);
    return fut;
  }
}
int main() {
   auto fut = make(100);
   task();
   std::cout << fut.get() << "n";
}

它简洁明了,避免了自己重新实现很多机制。不幸的是,这实际上是不合法的std::packaged_task因为它是仅移动的,而不是可复制的。

作为解决方法,我想出了以下内容,它根据std::promisestd::shared_ptr来实现事情:

#include <future>
#include <functional>
#include <iostream>
namespace {
  std::function<void()> task;
  std::future<int> make(int val) {
    auto test = std::make_shared<std::promise<int>>();
    task = [test,val]() {
      test->set_value(val);
      test.reset(); // This is important
    };
    return test->get_future();
  }
}
int main() {
   auto fut = make(100);
   task();
   std::cout << fut.get() << "n";
}

这"对我有用",但这实际上是正确的代码吗?有没有更好的方法来达到相同的净结果?

(请注意,第二个示例中std::shared_ptr的生命周期对于我的实际代码很重要。显然,我将采取措施防止两次调用相同的std::function)。

您的问题似乎源于类型不兼容:

std::function<void()> task;  // Notice this is not a package_task

那么,您为什么期望这有效呢?

task = std::move(test);  // when test is `std::packaged_task<int()>`

当我将任务更改为正确的类型时,它会按预期编译:

namespace {
  std::packaged_task<int()> task;          // Change this.
  std::future<int> make(int val) {
    auto test = std::packaged_task<int()>([val](){
      return val;
    });
    auto fut = test.get_future();
    task = std::move(test);              // This now compiles.
    return fut;
  }
}

就个人而言,由于类型很重要,我会从test中删除auto

namespace {
    std::packaged_task<int()> task;
    std::future<int> make(int val) {
        std::packaged_task<int()> test([val](){return val;});
        auto fut = test.get_future();
        task     = std::move(test);
        return fut;
    }
}