Click here to Skip to main content
15,883,946 members
Articles / Programming Languages / C++

Dynamically assigned and stored action sequence with handlers of the returned value, using boost::bind

Rate me:
Please Sign up or sign in to vote.
4.17/5 (5 votes)
24 Feb 2011CPOL9 min read 33.2K   186   11  
Module to dynamically assign, store, and call with handlers different functional objects: functors, functions, member functions.
#pragma once

#include "RetTypeSpecificator.hpp"


class ActionInterface
{
public:
	virtual ~ActionInterface(){}
	virtual void DoAction() = 0;
	virtual Base_Value_Storage * ReturnValue() = 0;	
};


template<typename ret_type, typename Action, typename Handler >
class ActionHolder : public ActionInterface
{
	Action m_Action;
	Handler * m_Handler;
	bool m_bDeleteHandler;
	RetValueStorage<ret_type> m_RetValueHolder;
public:
	ActionHolder(Action act, Handler * pHandler, bool bDeleteHandler) : m_Action(act),
		m_Handler(pHandler), m_bDeleteHandler(bDeleteHandler)
	{
		cout<<"Inside ActionHolder. RetValueStorage<ret_type> has ID =  "<<m_RetValueHolder.m_RetType<<endl;
	}
	~ActionHolder()
	{
		if(m_bDeleteHandler)
			delete m_Handler;
	}
	template<typename T>	
	void CallFunctor()
	{
		m_RetValueHolder.m_tData = m_Action();			
		(*m_Handler)(m_RetValueHolder.m_tData);
	}	

	template<>
	void CallFunctor<void>()
	{
		m_Action();		
	}	
	virtual void DoAction()
	{	
		CallFunctor<ret_type>();
		/*
		// unfortunately, runtime logic hasn't authority for templates ...

		TypeDeductor<void> voidType;
		TypeDeductor<ret_type> retType;
		if(voidType == retType)
			m_Action();
		else
		{
			m_RetValueHolder.m_tData = m_Action(); // here compiler becomes angry - cannot convert void to anything...
			if(m_bThereIsHandler)
				(*m_Handler)(m_RetValueHolder.m_tData);
		}
		*/
	}
	// this is the only (maybe) decent way to return outside data returned from m_Action call; 
	// after all we must remember what return type was defined in AddActionToSequence<ret_type> call in main.
	virtual Base_Value_Storage  * ReturnValue()
	{
		RetValueStorage<ret_type> * pRet = new RetValueStorage<ret_type>(m_RetValueHolder);
		return pRet;
	}
};

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Ukraine Ukraine
Now I'm working as a C++ developer and trainer and supporting
all my previously written applications.

Comments and Discussions