众所周知,std::result_of
函数调用时需要确定返回值的类型。它的 C++17 更新版本的工作原理类似 -invoke_result
#define _SILENCE_CXX17_RESULT_OF_DEPRECATION_WARNING
#include <type_traits>
int fn(int)
{
return int();
}
int main()
{
std::result_of<decltype(&fn)(int)>::type y; // y - это int
y = 5;
std::invoke_result<decltype(&fn),int>::type k;
k = 6;
return 0;
}
当使用 std::result_of<F(void)> 显式指定类型时,为什么在此答案中使用 typename?
template<typename F>
std::future<typename std::result_of<F()>::type>
runCmd(const std::string& cmd, F callback)
{
...
第二个问题:runCmd
一个lambda传递给函数,其类型由模板类型F描述,即类型是已知的,不需要通过decltype来识别,对吧?
补充指定问题的示例,代码decltype
如下:
#include <thread>
#include <future>
#include <string>
#include <iostream>
#include <type_traits>
void system()
{
std::cout << "Executing system with argument '" << "ls" << "'\n";
}
template<class F>
auto runCmd(F callback) -> std::future<decltype(callback())>
{
auto fut = std::async(std::launch::async, [callback] { system(); return callback(); });
return fut;
}
int main()
{
auto fut = runCmd([] { std::cout << "Executing callback\n"; });
fut.get();
}
typename
仅在模板中需要,在构建表单之前... T ... :: ...
,其中T
是模板参数或依赖于它的东西。这样编译器就可以在不查看
T
后面的内容::
、类型或其他内容(例如变量)的情况下确定。在 C++20 中,如果这已经很清楚,
typename
则不必编写它。如果你使用它
F
,那么是的。但这是可以做到的decltype(f(аргументы))
。