首页 > 解决方案 > C ++如何将具有不同数量参数的函数作为参数传递

问题描述

我正在编写一个 GLFW 库包装器 - 名为 GLFW_Facade 的类。有一个 RenderLoop 函数,它被提到是一个循环,其中将执行渲染函数。我需要将该渲染函数传递给 RenderLoop。我希望渲染函数可以采用不同数量的参数,所以我用模板制作了它。代码编译但没有链接。

起初我传递了一个带有不同数量参数的 std::function ,就像这样

template <typename... N>
void GLFW_Facade::RenderLoop(std::function<void, N...>& cb, N... params)

然后我为 std::function 创建了一个类包装器,它具有名为 Functor 的不同参数。

template <typename R, typename... Args>
class Functor {
public:
    typedef std::function<R(Args...)> FuncType;
    Functor(FuncType func) : mFunc(func) {}
    Functor& operator()(Args... args) {
        mFunc(args...);
        return *this;
    }
private:
    FuncType mFunc;
};

template <typename... N>
void GLFW_Facade::RenderLoop(Functor<void, N...>& cb, N... params) {
    CheckGLFWWindow();
    while (!glfwWindowShouldClose(m_Window)) {
        cb(params);
        ProcessCloseCondition();
        glfwSwapBuffers(m_Window);
        glfwPollEvents();
    }
}

///usage

Functor<void, int> renderfn(render);
glfw->RenderLoop<int>(renderfn, VAO);

错误 LNK2019 引用了不允许的外部符号“public: void __cdecl GLFW_Facade::RenderLoop(class Functor &,int)”(??$RenderLoop@H@GLFW_Facade@@QEAAXAEAV?$Functor@XH@@H@Z)函数主 .../main.obj 1

我期待这将被链接出来。

标签: c++templatesfunctorstd-functionparameter-list

解决方案


推荐阅读