【发布时间】:2018-08-28 16:59:38
【问题描述】:
昨天,我尝试编写一个基本渲染器,其中渲染器控制数据何时加载到着色器中,而可渲染对象不知道有关正在使用的着色器的任何信息。作为一个固执的人(并且没有足够的睡眠),我花了几个小时试图将函数指针发送到渲染器,保存,然后在适当的时间运行。直到后来我才意识到我正在尝试构建的是一个消息系统。这让我想知道,是否可以直接保存带有参数的 函数指针,以便以后在 c++ 中运行。
我最初的想法是这样的:
//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
}
我意识到 boost 可能支持某种类似的功能,但我想避免使用 boost。
这样的事情是否可能,一般设计会是什么样子,甚至可以将其用于将什么视为消息总线对于这样的事情是一种更加成熟的设计模式?
【问题讨论】:
-
或者只使用lambda,只要你按值捕获即可。
标签: c++ function class function-pointers