My current project requires quite a bit of function pointer passing to guarantee the flexibility desired. Given how messy and annoying I find functions pointers to be I decided to create a wrapper class listed below. Works fine, however it would be nice if their was a method so I could input the variables in an infinite list (well you know within reason) like a vaarg list.
I only have a basic understanding of templates so any help or suggestions would be appreciated. Honestly I rarely write a function with more than 4-5 input parameters so I could just go the extra mile and finish doing this but seems there should be a better way.
#ifndef FUNCTION_HANDLER_H
#define FUNCTION_HANDLER_H
//*********************************************
//Function Pointer Wrapper Class
//*********************************************
template<typename return_type,typename variable0, typename variable1 = void, typename variable2 = void>
class Function_Handler
{
protected:
return_type (*m_Function)(variable0,variable1,variable2);
public:
void set_function(return_type (*foo)(variable0,variable1,variable2)){m_Function = foo;}
return_type call_function(variable0 m, variable1 n, variable2 o){if(m_Function != nullptr)m_Function(m,n,o)else std::runtime_error("Function_Handler must be initialized");}
void clear(){m_Function = nullptr;}
Function_Handler(return_type (*foo)(variable0,variable1,variable2)){m_Function = foo;}
Function_Handler(){m_Function = nullptr;}
};
//*************************************************
//Specialization for only one variable
//*************************************************
template<typename return_type,typename variable0>
class Function_Handler<return_type,variable0,void,void>
{
protected:
return_type (*m_Function)(variable0);
public:
void set_function(return_type(*foo)(variable0)){m_Function = foo;}
return_type call_function(variable0 m){if(m_Function != nullptr)m_Function(m,n,o)else std::runtime_error("Function_Handler must be initialized");}
void clear(){m_Function = nullptr;}
Function_Handler(return_type (*foo)(variable0)){m_Function = foo;}
Function_Handler(){m_Function = nullptr;}
};
//************************************************
//Specialization for two variables
//************************************************
template<typename return_type,typename variable0, typename variable1 = void>
class Function_Handler<return_type,variable0,variable1,void>
{
protected:
return_type (*m_Function)(variable0,variable1);
public:
void set_function(return_type(*foo)(variable0,variable1)){m_Function = foo;}
return_type call_function(variable0 m,variable1 n){if(m_Function != nullptr)m_Function(m,n,o)else std::runtime_error("Function_Handler must be initialized");}
void clear(){m_Function = nullptr;}
Function_Handler(return_type (*foo)(variable0,variable1)){m_Function = foo;}
Function_Handler(){m_Function = nullptr;}
};
#endif