Skip to content

Instantly share code, notes, and snippets.

@wavewave
Last active December 22, 2015 02:39
Show Gist options
  • Save wavewave/6405175 to your computer and use it in GitHub Desktop.
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
#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