使用std::result_of确定模板实参的返回类型

using std::result_of to determine the return type of a template argument

本文关键字:实参 返回类型 std result of 使用      更新时间:2023-10-16

我认为这段代码是不言自明的,但基本上模板函数ExecFunc应该能够执行另一个函数并返回其结果。我知道我可以使用decltype而不是result_of达到类似的结果,但这个问题是为了理解为什么我所写的不工作:代码片段不能在gcc v4.9.2上编译。

这是我的:

#include <type_traits>
int f(int i)
{
   return i;
}
template<class F, class T>
auto ExecFunc(F f, T arg) -> typename std::result_of<F()>::type
{
  return f(arg);
}
int main() {
   auto a = ExecFunc(f, 3);
   return 0;
}

,这是编译器的输出:

prova.cpp: In function ‘int main()’:
prova.cpp:15:26: error: no matching function for call to ‘ExecFunc(int (&)(int), int)’
auto a = ExecFunc(f, 3);
                      ^
prova.cpp:15:26: note: candidate is:
prova.cpp:9:6: note: template<class F, class T> typename std::result_of<F()>::type ExecFunc(F, T)
 auto ExecFunc(F f, T arg) -> typename std::result_of<F()>::type
      ^
prova.cpp:9:6: note:   template argument deduction/substitution failed:
prova.cpp: In substitution of ‘template<class F, class T> typename std::result_of<F()>::type ExecFunc(F, T) [with F = int (*)(int); T = int]’:
prova.cpp:15:26:   required from here
prova.cpp:9:6: error: no type named ‘type’ in ‘class std::result_of<int (*())(int)>’

注意:这个问题可能看起来像这个问题的副本,但接受的解决方案对我不起作用(至少,据我所知,我已经将解决方案纳入了我的代码中)。

您的函数是int f(int i),但您正在调用F(),这是未知的。std::result_of<F()>::type应该是std::result_of<F(T)>::type

生活例子

问题是result_of的参数,它应该是:

-> typename std::result_of<F(T)>::type

这是使用decltype

的最佳时机
template<class F, class T>
auto ExecFunc(F f, T arg) -> decltype(f(arg))