有没有办法知道将来是否会抛出get()?

有没有办法知道未来是否会在get()上出现?

说我有一些这样的东西:

#include <cstdlib>
#include <future>
#include <stdexcept>
#include <iostream>

int main() {
  srand(time(0));
  auto randomSuccess = [] {
             if (rand() >= rand())
                  throw std::runtime_error("Random exception");
             };
  auto f = std::async(std::launch::deferred,randomSuccess);

  f.wait();
  // from here,the future is valid
  std::cout << "Now future is " << (f.valid() ? "valid" : "not valid yet") << std::endl;

  f.get(); // how to know if this will throw?
}

我只想“窥探”未来的内部状态,就像bool valid() const noexcept;那样,通过保持未来不受干扰(函数为const),这就是为什么放置try/catch块不是什么我想做。

zxj3125 回答:有没有办法知道将来是否会抛出get()?

您可能会做一些体操以获得结果:

template <typename T>
bool will_throw(std::future<T>& fut)
{
    std::promise<T> promise;
    try {
        if constexpr (std::is_void<T>::value) {
            fut.get();
            promise.set_value();
        } else {
            promise.set_value(fut.get());
        }
        fut = promise.get_future(); // Restore future value
        return false;
    } catch (...) {
        promise.set_exception(std::current_exception());
        fut = promise.get_future(); // Restore future exception
        return true;
    }
}

Demo

,

基于与@ Jarod42相同的思想,而无需c ++ 17支持

template <class T>
bool will_throw(std::future<T> &f) {
    bool throws = false;
    auto new_f = std::async(std::launch::deferred,[&throws,&f] () {
       try {
           return f.get();
       } catch (...) {
           throws = true;
           throw;
       }
    });

    new_f.wait();

    f = std::move(new_f);

    return throws;
}
本文链接:https://www.f2er.com/3152804.html

大家都在问