如何在std :: Future中使用velltype

How to use decltype in std::future?

本文关键字:velltype Future std      更新时间:2023-10-16

在此代码中,如何在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_ofstd::invoke_result_t<decltype(bar), int>好。非常直观。