This is an excerpt from my playing with genetic algorithm. I wrote a class for that. You can check it out here if you think you need it, it's free. Genetic algorithm requires custom made objective function and that's what I needed this feature for.
Here is what I did. Declaration:
#include <functional>
template<class CLASS_TYPE>
class ClassName
{
public:
// type definition for readability
using callback_function = std::function<int(CLASS_TYPE*, int)>;
// callback setter
void setCallback(callback_function callbackFunction, CLASS_TYPE* object);
// some function from which callback will get called
int someFunction(int argument);
private:
// member variables where callbacks are stored
callback_function m_callbackFunction;
CLASS_TYPE* m_callbackFunctionObject;
}
Implementation:
template<CLASS_TYPE>
void ClassName<CLASS_TYPE>::setCallback(callback_function callbackFunction, CLASS_TYPE* object)
{
// this is how you can store callback functions and objects to use later
m_callbackFunction = callbackFunction;
m_callbackFunctionObject = object;
}
template<CLASS_TYPE>
int ClassName<CLASS_TYPE>::someFunction(int argument)
{
// this is how you call callback function and pass an argument
result = m_callbackFunction(m_callbackFunctionObject, argument);
return result * 2;
}
Class with callback function:
class CallbackClass
{
public:
// a function matching the signature std::function<int(CallbackClass*, int)>;
int callbackFunction(int argument)
{
// do something with arguments, return something
return argument + 2;
}
}
And an example of use:
CallbackClass callbackObject;
ClassName<CallbackClass> classObject;
classObject.setCallback(&CallbackClass::callbackFunction, callbackObject);
// will call ClassName::someFunction, which will call CallbackClass::callbackFunction of the object callbackObject
int result = classObject.someFunction(1); // result = ((1+2)*2)
Previous:
Solving Sudoku with A*
Next:
How to create tea timer for Linux console