Method-Function-Pointer

#include <iostream>

template<typename R, typename M>
class MemberFunction
{
public:
	MemberFunction(R (M::*method)(), M* instance):
		_method(method),
		_instance(instance)
	{
	}

	R operator()()
	{
		return (_instance->*_method)(); // ->* pointer-to-member selection operator
	}

private:
	R (M::*_method)();
	M* _instance;
};


template<typename R, typename M>
MemberFunction<R, M> createMemberFunction(R (M::*method)(), M* instance)
{
	return MemberFunction<R, M>(method, instance);
}



struct Test
{
	void test()
	{
		std::cout << "blubb" << std::endl;
	}
};


int main()
{
	Test t;

	createMemberFunction(&Test::test, &t)();

	return 0;
}
</code>

<code cpp>
#include <iostream>

template <typename Sig>
class MemberFunctionImplBase;

template <typename R, typename A>
class MemberFunctionImplBase<R(A)>
{
public:
	typedef R ReturnType;
	typedef A ArgumentType;

	virtual ~MemberFunctionImplBase()
	{};

	virtual MemberFunctionImplBase<R(A)>* clone() = 0;

	virtual R operator()(A a) = 0;
};

template <typename R, typename M, typename A>
class MemberFunctionImpl: public MemberFunctionImplBase<R(A)>
{
public:
	MemberFunctionImpl(R (M::*method)(A), M* instance):
		_method(method),
		_instance(instance)
	{}

	MemberFunctionImplBase<R(A)>* clone()
	{
		return new MemberFunctionImpl(_method, _instance);
	}

	R operator()(A a)
	{
		return (_instance->*_method)(a);
	}

private:
	R (M::*_method)(A);
	M* _instance;
};

template <typename Sig>
class MemberFunction
{
public:
	typedef typename MemberFunctionImplBase<Sig>::ReturnType ReturnType;
	typedef typename MemberFunctionImplBase<Sig>::ArgumentType ArgumentType;

	MemberFunction():
		_f(0)
	{}

	MemberFunction(MemberFunctionImplBase<Sig>* f):
		_f(f)
	{}

	MemberFunction(const MemberFunction& other)
	{
		_f = other._f->clone();
	}

	~MemberFunction()
	{
		delete _f;
	}

	ReturnType operator()(ArgumentType a)
	{
		return (*_f)(a);
	}

	MemberFunction<Sig>& operator=(const MemberFunction<Sig>& other)
	{
		if (_f) delete _f;
		_f = other._f->clone();

		return *this;
	}

private:
	MemberFunctionImplBase<Sig>* _f;
};

template<typename R, typename M, typename A>
MemberFunction<R(A)> createMemberFunction(R (M::*method)(A), M* instance)
{
	return MemberFunction<R(A)>(new MemberFunctionImpl<R, M, A>(method, instance));
};


struct X
{
	void x(int j)
	{
		std::cout << "j = " << j << std::endl;
	}
};

int main()
{
	X x;

	MemberFunction<void(int)> xf = createMemberFunction(&X::x, &x);
	(xf)(42);

	return 0;
}

  • Zuletzt geändert: 2019-03-31 15:23