c++ - Writing a template function that evaluates a lambda function with any return type? -


i want write 'evaluation' function takes input function of unspecified return type takes integer, , integer call function with.

what i've come following:

#include <functional> template<typename t> t eval(function<t(int)> f, int x) {     return f(x); } 

let's have auto func = [] (int x) -> long { return (long)x * x; } want evaluate using above function. way used template functions before call other function , let compiler deduce type.

however, doesn't work eval function. eval<long>(func, 5) compiles , works fine, eval(func, 5) not:

aufgaben10.5.cpp:23:25: error: no matching function call 'eval(main()::__lambda0&, int)'      cout << eval(func, 5) << endl;                          ^ aufgaben10.5.cpp:23:25: note: candidate is: aufgaben10.5.cpp:8:3: note: template<class t> t eval(std::function<t(int)>, int)  t eval(function<t(int)> f, int x) {    ^ aufgaben10.5.cpp:8:3: note:   template argument deduction/substitution failed: aufgaben10.5.cpp:23:25: note:   'main()::__lambda0' not derived 'std::function<t(int)>'      cout << eval(func, 5) << endl; 

is there way write template function has same return type lambda function without explicitly passing type template, can call eval(func, 5)?

why not use decltype?

template<typename function> auto eval(function&& f, int x) -> decltype(std::forward<function>(f)(x)) {    return std::forward<function>(f)(x); } 

Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -