c++ - std::function in template function -


i trying write template function can accept functor parameter , call afterwards. program follows:

#include <iostream> #include <functional> using namespace std;  template<typename r, typename... args> r call(function<r(args...)> fun, args... args) {     cout << "call@ " << __line__ <<endl;     return fun(args...); }  int main() {     cout << call(std::plus<int>(),1,2) <<endl;     return 0; } 

the g++ compplains:

g++ -c -wall -std=c++0x -i../include a.cpp -o a.o a.cpp: in function ‘int main()’: a.cpp:16:38: error: no matching function call ‘call(std::plus<int>, int, int)’ a.cpp:16:38: note: candidate is: a.cpp:7:3: note: template<class r, class ... args> r call(std::function<_res(_argtypes ...)>, args ...) a.cpp:7:3: note:   template argument deduction/substitution failed: a.cpp:16:38: note:   ‘std::plus<int>’ not derived ‘std::function<_res(_argtypes ...)>’ make: *** [a.o] error 1 

i suppose std::plus<int>() deduced std::function<int(int,int)>, didn't. why that? gcc gcc version 4.7.2 20120921 (red hat 4.7.2-2) (gcc)

i suppose std::plus() deduced std::function

no. not deduced given have passed object of type std::plus<int>.

in case, you not need use std::function, use when storing different functions/function objects can called specific signature.

with that, can have call function accept function/function object directly, original type deduced, without using std::function. also, might want use perfect forwarding when accepting parameters , use std::forward when passing them arguments function/function object. should use return type of function return type of call. use c++11's trailing return type decltype that.

#include <iostream> #include <functional> using namespace std;  template<typename r, typename... args> auto call(r fun, args&&... args) -> decltype(fun(std::forward<args>(args)...)) {     cout << "call@ " << __line__ <<endl;     return fun(std::forward<args>(args)...); }  int main() {     cout << call(std::plus<int>(),1,2) <<endl;     return 0; } 

live code


as @jan hudec has commented, __line__ in there result same in calls call, whatever function passed.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -