Using std :: result_of to determine the return type of template argument

I think the code snippet is self-explanatory, but basically a template function ExecFunc

should be able to execute another function and return its result. I know that I can use decltype

instead to achieve similar results result_of

, but this question is to understand why what I wrote does not work: the snippet does not compile on gcc v4.9.2.

This is what I have:

#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;
}

      

and this is the compiler output:

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)>’

      

NB this question may look like a duplicate of this , but the accepted solution doesn't work for me (at least as far as I can tell, I've included the solution in my code).

+3


source to share


3 answers


You have a function int f(int i)

, but you are calling F()

that is unknown. std::result_of<F()>::type

should be std::result_of<F(T)>::type

.



Live example

+4


source


The problem is in the parameter result_of

, it should be:



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

      

+2


source


This is the perfect time to use decltype

template<class F, class T>
auto ExecFunc(F f, T arg) -> decltype(f(arg))

      

0


source







All Articles