Yesterday, I was trying to program a basic renderer where the renderer controlled when data was loaded into a shader without the renderable object knowing anything about the shader being used. Being a stubborn person (and not running on enough sleep), I spent several hours trying to have function pointers sent to the renderer, saved, then run at the appropriate time. It wasn't until later that I realized what I was trying to build was a message system. It got me wondering, though, is it possible to save function pointers with arguments directly to be run at a later time in c++.
My original idea looked something like this:
// set up libraries and variables
Renderer renderer();
renderable obj();
mat4 viewMatrix();
// renderer returns and object id
int objID = renderer.loadObj(obj)
int main()
{
//do stuff
while(running)
{
//do stuff
renderer.pushInstruction(//some instruction);
renderer.render();
}
}
// functionPtr.h
#include <functional>
class storableFunction
{
public:
virtual ~storableFunction = 0;
virtual void call() = 0;
};
template<class type>
class functionPtr : public storableFunction
{
std::function<type> func;
public:
functionPtr(std::function<type> func)
: func(func) {}
void call() { func(); }
};
//renderer.h
struct modelObj
{
// model data and attached shader obj
std::queue<storableFunction> instruction;
}
class renderer
{
std::map<int, modelObj> models;
public:
// renderer functions
void pushInputDataInstruction(int id, //function, arg1, arg2);
// this was overloaded because I did not know what type the second argument would be
// pushInputDataInstruction implementation in .cpp
{
models[id].instruction.push(functionPtr(std::bind(//method with args)))
}
void render();
};
//implantation in .cpp
{
for(// all models)
//bind all data
applyInstructions(id);
// this would call all the instructrions using functionptr.call() in the queue and clear the queue
draw();
// unbind all data
}
I realize that boost probably supports some kind of similar functionality, but I wanted to avoid using boost.
Is something like this possible, what would the general design look like, and what would it even be used for seeing as a message bus is a much more proven design pattern for something like this?