Advertisement
Guest User

oldstyle

a guest
Feb 24th, 2010
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | None | 0 0
  1.  
  2.  
  3. #include <boost/preprocessor/repetition/repeat.hpp>
  4. #include <boost/preprocessor/repetition/enum_params.hpp>
  5. #include <boost/preprocessor/repetition/enum_binary_params.hpp>
  6. #include <boost/preprocessor/repetition/enum_trailing_params.hpp>
  7.  
  8. #include <iostream>
  9.  
  10.  
  11. #ifdef __GNUC__
  12. # define MACRO_THREAD_LOCAL __thread
  13. #elif _MSC_VER
  14. # define MACRO_THREAD_LOCAL __declspec(thread)
  15. #else
  16. # error No idea how you use TLS on other compilers.
  17. #endif
  18.  
  19.  
  20. #define MACRO_CREATE_CALLBACK_STRUCT(z, n, data) \
  21. template<typename ObjT, typename R BOOST_PP_ENUM_TRAILING_PARAMS(n, typename ArgT)> \
  22. class Callback ## n \
  23. { \
  24. public: \
  25.     typedef R (*CallbackFunc)(BOOST_PP_ENUM_PARAMS(n, ArgT)); \
  26.  \
  27. private: \
  28.     static MACRO_THREAD_LOCAL ObjT const* obj; \
  29.  \
  30.     static R theCallbackFunc(BOOST_PP_ENUM_BINARY_PARAMS(n, ArgT, arg)) \
  31.     { \
  32.         if(obj) \
  33.         { \
  34.             (*obj)(BOOST_PP_ENUM_PARAMS(n, arg)); \
  35.         } \
  36.     } \
  37. public: \
  38.     static CallbackFunc use(ObjT const& o) \
  39.     { \
  40.         obj = &o; \
  41.         return &theCallbackFunc; \
  42.     } \
  43. }; \
  44.  \
  45. template<typename ObjT, typename R BOOST_PP_ENUM_TRAILING_PARAMS(n, typename ArgT)> \
  46. MACRO_THREAD_LOCAL ObjT const* Callback ## n<ObjT, R BOOST_PP_ENUM_TRAILING_PARAMS(n, ArgT)>::obj = 0; \
  47.  \
  48. template<typename R BOOST_PP_ENUM_TRAILING_PARAMS(n, typename ArgT), typename ObjT> \
  49. typename Callback ## n<ObjT, R BOOST_PP_ENUM_TRAILING_PARAMS(n, ArgT)>::CallbackFunc \
  50. useCCallback ## n(ObjT const& obj) \
  51. { \
  52.     return Callback ## n<ObjT, R BOOST_PP_ENUM_TRAILING_PARAMS(n, ArgT)>::use(obj); \
  53. } \
  54.  
  55.  
  56. #define MACRO_CREATE_C_CALLBACK_HELPER(n) BOOST_PP_REPEAT(n, MACRO_CREATE_CALLBACK_STRUCT, )
  57.  
  58.  
  59. // Create callback helper for up to 9 parameters.
  60. MACRO_CREATE_C_CALLBACK_HELPER(10)
  61.  
  62.  
  63. typedef void (*CallbackPtr)(char const*);
  64.  
  65. void cFunction(CallbackPtr ptr)
  66. {
  67.     ptr("Hello!");
  68. }
  69.  
  70.  
  71. struct Output
  72. {
  73.     char const* user;
  74.  
  75.     void operator ()(char const* message) const
  76.     {
  77.         std::cout << user << ": " << message << std::endl;
  78.     }
  79. };
  80.  
  81.  
  82. int main()
  83. {  
  84.     Output output = { "KFS1_GOD" };
  85.     cFunction(useCCallback1<void, char const*>(output));
  86.  
  87.     return 0;
  88. }
  89.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement