template <typename ReturnType, typename ArgType>
struct closure_entity_base
{
virtual ReturnType operator()(ArgType a)=0;
virtual closure_entity_base* clone()const=0;
};
template <class ClassType, typename ReturnType, typename ArgType>
struct closure_entity : closure_entity_base<ReturnType, ArgType>
{
ReturnType operator()(ArgType a)
{
return (m_object.*m_fp)(a);
}
closure_entity(ClassType& object, ReturnType (ClassType::*fp)(ArgType))
:m_object(object), m_fp(fp)
{}
virtual closure_entity_base<ReturnType, ArgType>* clone()const
{
return new closure_entity(*this);
}
ClassType& m_object;
ReturnType (ClassType::*m_fp)(ArgType);
};
template <typename ReturnType, typename ArgType>
struct closure
{
template <class ClassType>
closure(ClassType& object, ReturnType(ClassType::*fp)(ArgType))
:entity(new closure_entity<ClassType, ReturnType, ArgType>(object, fp))
{}
~closure(){delete entity;}
closure(const closure& src)
{
entity = src.entity->clone();
}
closure& operator=(const closure& src)
{
if(&src!=this)
{
delete entity;
entity = src.entity->clone();
}
return *this;
}
ReturnType operator()(ArgType a)
{
return (*entity)(a);
}
closure_entity_base<ReturnType, ArgType>* entity;
};
class Test
{
public:
int foo(int x){return x*x;}
};
#include <iostream>
int main( void )
{
Test t;
closure<int, int> c(t, &Test::foo);
std::cout << c(10) << '\n';
return 0;
}