Guest User

Untitled

a guest
May 28th, 2012
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. Generic wrapper to return last parameter of function in C
  2. void my_fun(
  3. const in_class & in_param_1,
  4. const in_class & in_param_2,
  5. const in_class & in_param_3,
  6. out_class & out_param);
  7.  
  8. out_class my_out;
  9. my_fun(my_in1,my_in2,my_in3,my_out);
  10.  
  11. out_class my_out = generic_wrapper(&my_fun,my_in1,my_in2,my_in3);
  12.  
  13. template<class T1, class Out>
  14. Out generic_wrapper(void (*f)(const T1 &, Out &), const T1 & t1) {
  15. Out out;
  16. f(t1,out);
  17. return out;
  18. }
  19.  
  20. template<class T1, class T2, class Out>
  21. Out generic_wrapper(void (*f)(const T1 &, const T2 &, Out &), const T1 & t1, const T1 & t2) {
  22. Out out;
  23. f(t1,t2,out);
  24. return out;
  25. }
  26.  
  27. // .....
  28.  
  29. template<class T1, class T2, class T3, class T4, class T5, class Out>
  30. Out generic_wrapper(void (*f)(const T1 &, const T2 &, const T3 &, const T4 &, const T5 &, Out &), const T1 & t1, const T1 & t2, const T3 & t3, const T4 & t4, const T5 & t5) {
  31. Out out;
  32. f(t1,t2,t3,t4,t5,out);
  33. return out;
  34. }
  35.  
  36. template <class Func, class ...Args>
  37. typename last_argument_type<Func>::type wrapper(Func f, Args&& ...args)
  38. {
  39. typename last_argument_type<Func>::type result;
  40. f(std::forward<Args>(args)..., result);
  41. return result;
  42. }
  43.  
  44. //typedefs last type in T... as type
  45. template <class ...T>
  46. struct last_type;
  47.  
  48. template <class T, class ...U>
  49. struct last_type<T, U...> { typedef typename last_type<U...>::type type; };
  50.  
  51. template <class T>
  52. struct last_type<T> { typedef T type; };
  53.  
  54. //typedefs the type of the last argument of a function as type
  55. //removes reference
  56. //e.g void(int, float, double&) -> type = double
  57. template <class ...Args>
  58. struct last_argument_type;
  59.  
  60. template <class Ret, class ...Args>
  61. struct last_argument_type<Ret(*)(Args...)> {
  62. typedef typename std::remove_reference<typename last_type<Args...>::type>::type type;
  63. };
  64.  
  65. template <class Out, class... Ins>
  66. Out generic_wrapper(void (*fun)(const Ins&... , Out&), const Ins&... ins)
  67. {
  68. Out out;
  69. fun(ins..., out);
  70. return out;
  71. }
  72.  
  73. int main()
  74. {
  75. in_class in;
  76. out_class out1a = generic_wrapper(my_fun_1, in); // fails to compile...
  77. out_class out1b = generic_wrapper<out_class, in_class>(my_fun_1, in); // works...
  78. return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment