C ++ 11: Templated wrapper function

I am trying to create a general wrapper function that takes any function as an argument, as well as their parameters. Just something like a std::thread constructor.

My current code is:

 #include <iostream> using namespace std; template<typename FUNCTION, typename... ARGS> void wrapper(FUNCTION&& func, ARGS&&... args) { cout << "WRAPPER: BEFORE" << endl; auto res = func(args...); cout << "WRAPPER: AFTER" << endl; //return res; } int dummy(int a, int b) { cout << a << '+' << b << '=' << (a + b) << endl; return a + b; } int main(void) { dummy(3, 4); wrapper(dummy, 3, 4); } 

The wrapping function itself works. It calls the given function object ( std::function , a functor, or simply a β€œnormal” function) with the given arguments. But I also like to return the return value.

This should work with remote return -statement, but unfortunately I don't know how to declare the return type of wrapper functions.

I tried a lot of things (e.g. with decltype ) but nothing worked. Now my question is: how can I get the following code?

 #include <iostream> template<typename FUNCTION, typename... ARGS> ??? wrapper(FUNCTION&& func, ARGS&&... args) { cout << "WRAPPER: BEFORE" << endl; auto res = func(args...); cout << "WRAPPER: AFTER" << endl; return res; } int dummy(int a, int b) { cout << a << '+' << b << '=' << (a + b) << endl; return a + b; } int main(void) { dummy(3, 4); cout << "WRAPPERS RES IS: " << wrapper(dummy, 3, 4) << endl; } 

I think the code should work except ??? .

Thanks for any ideas.

Relations Kevin

+6
source share
2 answers

Use std::result_of :

 template <typename F, typename ...Args> typename std::result_of<F &&(Args &&...)>::type wrapper(F && f, Args &&... args) { return std::forward<F>(f)(std::forward<Args>(args)...); } 

In C ++ 14, you can use the result_of_t alias:

 template <typename F, typename ...Args> std::result_of_t<F &&(Args &&...)> wrapper(F && f, Args &&... args) { return std::forward<F>(f)(std::forward<Args>(args)...); } 

Or you can use the return of the return type:

 template <typename F, typename ...Args> decltype(auto) wrapper(F && f, Args &&... args) { std::cout << "before\n"; auto && res = std::forward<F>(f)(std::forward<Args>(args)...); std::cout << "after\n"; return res; } 
+14
source

You can use decltype with C ++ 11 automatic return type:

 template<typename FUNCTION, typename... ARGS> auto wrapper(FUNCTION&& func, ARGS&&... args) -> decltype(func(std::forward<ARGS>(args)...)) 

Live demo


And in C ++ 14 just do:

 template<typename FUNCTION, typename... ARGS> decltype(auto) wrapper(FUNCTION&& func, ARGS&&... args) 

Live demo

+7
source

Source: https://habr.com/ru/post/974334/


All Articles