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