我试图创建一个RenderClass,其中一个函数从Thread调用,它计算所有内容并将函数调用插入 vector ,而另一个Thread调用RenderClass wich的函数,然后调用在 vector 上被插入的每个函数,这甚至可能?我的代码也没有给我提供智能感知错误,而只是一些奇怪的C3867错误,在我看来,当尝试编译时,这是没有道理的。
我已经尝试过使用模板功能
就像删除RenderClass::*函数
template<typename Function, typename ...ARGS>
void QueueRenderFunction(Function *function, ARGS... args)
但不能使它工作:/
在这里我测试了整个测试程序...
#include <Windows.h>
#include <iostream>
#include <functional>
#include <string>
#include <vector>
#include <mutex>
class Vector3 {
float x, y, z;
};
class RenderClass
{
public:
template<typename Function, typename ...ARGS>
void QueueRenderFunction(Function RenderClass::*function, ARGS... args)
{
_RenderList.push_back(std::forward<Function>(function, args...));
}
void CallRenderFunctions()
{
std::lock_guard<std::recursive_mutex> l(renderlist_mtx);
for (auto&& Function : RenderList)
Function();
}
//just as examplecode
void DRAWCIRCLE(Vector3 Position, float Range) {
std::cout << Range << std::endl;
}
void DRAWSTRING(Vector3 Position, std::string String) {
std::cout << String << std::endl;
}
void QueueDrawings() {
//begin new Renderlist
_RenderList.clear();
//some drawing calcs
//some Position
Vector3 Position;
QueueRenderFunction(DRAWCIRCLE, Position, 100.f);
QueueRenderFunction(DRAWSTRING, Position,"Name");
std::lock_guard<std::recursive_mutex> l(renderlist_mtx);
RenderList = _RenderList;
}
private:
std::recursive_mutex renderlist_mtx;
std::vector<std::function<void()>> RenderList;
std::vector<std::function<void()>> _RenderList;
};
RenderClass* Renderer = new RenderClass();
void Render() {
while (true)
{
Renderer->CallRenderFunctions();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
int main() {
std::thread RenderThread(Render);
while (true)
{
Renderer->QueueDrawings();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return 0;
}
就像说我得到这个错误例如:
严重性代码说明项目文件行抑制状态
错误C3867'RenderClass::DRAWCIRCLE':非标准语法;使用“&”创建指向成员的指针
然后尝试&DRAWCIRCLE就给了我
错误C2276'&':对绑定(bind)成员函数表达式的非法操作
那就是让我说这在我看来没有任何意义的原因
最佳答案
您的问题是您有一个std::vector<std::function<void()>>
,这很好,但是您需要添加一些扩充。 std::bind是您的 friend 。
这段代码应该可以解决问题。
template<typename Function, typename ...ARGS>
void QueueRenderFunction(Function function, ARGS... args)
{
_RenderList.push_back(std::bind(function, args...));
}
您可能还想将放到渲染列表中的函数定义为没有函数,然后将其作为参数传递。
附带说明,您可能想使用
RenderList.swap(_RenderList);
减少复制。