[英]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>
。 非常直观。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.