Last active
December 22, 2015 02:39
-
-
Save wavewave/6405175 to your computer and use it in GitHub Desktop.
closure in C++ : capturing a variable and send it as a function pointer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <boost/optional.hpp> | |
| #include <boost/bind.hpp> | |
| #include <boost/preprocessor/slot/counter.hpp> | |
| #include <iostream> | |
| #include <ostream> | |
| using namespace std; | |
| template<unsigned ID,typename Functor> | |
| boost::optional<Functor> &get_local() | |
| { | |
| static boost::optional<Functor> local; | |
| return local; | |
| } | |
| template<unsigned ID,typename Functor> | |
| typename Functor::result_type wrapper() | |
| { | |
| return get_local<ID,Functor>().get()(); | |
| } | |
| template<typename ReturnType> | |
| struct Func | |
| { | |
| typedef ReturnType (*type)(); | |
| }; | |
| template<unsigned ID,typename Functor> | |
| typename Func<typename Functor::result_type>::type get_wrapper(Functor f) | |
| { | |
| (get_local<ID,Functor>()) = f; | |
| return wrapper<ID,Functor>; | |
| } | |
| // ---------------------------------------------------------------------- | |
| void test(void (*fptr)()) | |
| { | |
| fptr(); | |
| } | |
| struct SomeStruct | |
| { | |
| int data; | |
| void some_method() | |
| { | |
| cout << data << endl; | |
| } | |
| void another_method() | |
| { | |
| cout << -data << endl; | |
| } | |
| }; | |
| void Test( SomeStruct& s ) | |
| { | |
| #include BOOST_PP_UPDATE_COUNTER() | |
| test(get_wrapper<BOOST_PP_COUNTER>( boost::bind(&SomeStruct::some_method, s ))); | |
| #include BOOST_PP_UPDATE_COUNTER() | |
| test(get_wrapper<BOOST_PP_COUNTER>( boost::bind(&SomeStruct::another_method, s ))); | |
| } | |
| int main() | |
| { | |
| SomeStruct local[] = { {11}, {22}, {33} }; | |
| Test( local[0] ); | |
| Test( local[1] ); | |
| Test( local[2] ); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment