Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 17th, 2012  |  syntax: None  |  size: 1.54 KB  |  hits: 38  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. functions as template argument, plus variadic template argument
  2. template <typename R, typename Arg1, typename Arg2, R F(Arg1, Args)>
  3. struct wrapper
  4.        
  5. // This won't work
  6. template <typename R, typename... Args, R F(Args...)>
  7. struct wrapper
  8.        
  9. template <typename R, typename... Args>
  10. struct func_type<R(Args...)>
  11. {
  12.   // Inner function wrapper take the function pointer as a template argument
  13.   template <R F(Args...)>
  14.   struct func
  15.   {
  16.     static int call( lua_State *L )
  17.     {
  18.       // extract arguments from L
  19.       F(/*arguments*/);
  20.       return 1;
  21.     }
  22.   };
  23. };
  24.        
  25. double sin(double d) {}
  26.        
  27. func_type<decltype(sin)>::func<sin>::apply
  28.        
  29. template<typename Signature>
  30. struct wrapper; // no base template
  31.  
  32. template<typename Ret, typename... Args>
  33. struct wrapper<Ret(Args...)> {
  34.     // instantiated for any function type
  35. };
  36.        
  37. template<typename Sig, Sig& S>
  38. struct wrapper;
  39.  
  40. template<typename Ret, typename... Args, Ret(&P)(Args...)>
  41. struct wrapper<Ret(Args...), P> {
  42.     int
  43.     static apply(lua_State*)
  44.     {
  45.         // pop arguments
  46.         // Ret result = P(args...);
  47.         // push result & return
  48.         return 1;
  49.     }
  50. };
  51.  
  52. // &wrapper<decltype(sin), sin>::apply is your Lua-style wrapper function.
  53.        
  54. #include <iostream>
  55. #include <boost/typeof/typeof.hpp>
  56.  
  57. void f(int b, double c, std::string const& g)
  58. {
  59.   std::cout << "f(): " << g << std::endl;
  60. }
  61.  
  62. template <typename F, F* addr>
  63. struct wrapper
  64. {
  65.   void operator()()
  66.   {
  67.     std::string bar("bar");
  68.     (*addr)(1, 10., bar);
  69.   }  
  70. };
  71.  
  72. int main(void)
  73. {
  74.   wrapper<BOOST_TYPEOF(f), &f> w;
  75.   w();
  76.   return 0;
  77. }