C++ 有没有办法知道未来是否会发生get()?
有没有办法知道未来是否会发生C++ 有没有办法知道未来是否会发生get()?,c++,exception,future,C++,Exception,Future,有没有办法知道未来是否会发生get() 假设我有一些像这样的: #include <cstdlib> #include <future> #include <stdexcept> #include <iostream> int main() { srand(time(0)); auto randomSuccess = [] { if (rand() >= rand())
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?
}
#包括
#包括
#包括
#包括
int main(){
srand(时间(0));
自动随机成功=[]{
如果(rand()>=rand())
抛出std::runtime_错误(“随机异常”);
};
自动f=std::async(std::launch::deferred,randomSuccess);
f、 等待();
//从这里开始,未来是有效的
std::cout你可以做一些体操来获得结果:
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;
}
}
模板
布尔将抛出(标准::未来和未来)
{
承诺;
试一试{
如果constexpr(std::is_void::value){
fut.get();
promise.set_value();
}否则{
promise.set_值(fut.get());
}
fut=promise.get_future();//恢复未来值
返回false;
}捕获(…){
set_exception(std::current_exception());
fut=promise.get_future();//还原未来异常
返回true;
}
}
基于与@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;
}
模板
布尔将抛出(标准::未来&f){
bool=false;
自动新建\u f=std::async(std::launch::deferred,[&throws,&f](){
试一试{
返回f.get();
}捕获(…){
抛出=真;
投掷;
}
});
新的等等;
f=标准::移动(新的);
回击;
}
使用尝试
/捕获
?只有一种方法可以找到。添加了更多解释以使问题更清楚。该代码只是一个虚拟演示代码,如果存在,我希望有一个通用解决方案…您无法确定任意代码段是否会引发异常。如果可以,您可以解决,这是你不能。不尊重康斯特内斯的条件,但这是个好主意