如何在std :: Future中使用velltype
How to use decltype in std::future?
在此代码中,如何在std::future
中使用decltype
来推断bar()
的返回类型?尽管直接使用std::future<int>
有效,但我想知道如何在这种情况下使用decltype
。
#include <iostream>
#include <future>
int bar(int a)
{
return 50;
}
int main()
{
std::packaged_task<decltype(bar)> task(bar);
//std::future<decltype(bar(int))> f = task.get_future(); //doesn't work need to do something like this
std::future<int> f = task.get_future(); //works
std::thread t1(std::move(task), 10);
t1.detach();
int val = f.get();
std::cout << val << "n";
return 0;
}
另外,在std::packaged_task
中使用decltype
是否正确?
请注意,您可以使用auto
:
auto f = task.get_future();
一切都按预期工作。
decltype
用于检测表达式的类型。在这种情况下,bar(int)
不是有效的表达式。您可以使用decltype(bar(0))
。
另外,您可以使用专用工具来确定功能调用的结果。由于您标记为C 11,因此可以使用typename std::result_of<decltype(bar)*(int)>::type
(当然,您需要#include <type_traits>
(。
为了将来的读者受益:我想从C 17的角度解决这个问题。result_of
是期望F(Args...)
表格的模板参数,因为该功能类型是返回类型,并且非常有限。在C 17中,引入了invoke_result
,并且比result_of
:std::invoke_result_t<decltype(bar), int>
好。非常直观。
相关文章:
- 架构决策:返回std::future还是提供回调
- 使用用户定义的参数调用future/async并调用类方法
- std::p romise::set_value() 和 std::future::wait() 是否提供内存围栏?
- 修改在 std::future 的 lambda 中引用捕获的值
- 从 T 创建 std::future 的最佳方式<T>
- C++ std::future没有被调用
- 对于等待以 std::future wait() 返回的函数的 CPU 使用率或检查标志在循环中休眠一段时间哪个更好?
- 如何使用 boost::future 重新抛出 std::exception_ptr 存储的原始异常?
- Make zmqpp::socket::connect a std::future
- std::future可以比std::promise活得更长吗
- std::future::get()或std::future::wait()是std::thread::join()的替
- 使用 future 时获取 C2280(尝试引用已删除的函数)
- 当 std::future 准备好被检索时发出信号主线程
- C++ std::future 方法应该<T>命名为 is_ready() 还是 ready()?
- 为什么printf会导致与future.get的死锁,而cout则不会?
- 当多次调用时,"std::future::then"的行为是什么?
- 使用 std::vector<std::future<int>> 和 std::async 启动几个线程时中止
- 使用 std::future 的不完整类型无效使用
- boost::future::那它是如何实现的?
- 如何在std :: Future中使用velltype