c++ - 类内的模板方法返回一个未定义的引用
问题描述
我的标题中有这个类render_object.hpp
:
class RenderObject {
public:
struct OGLVertexAttribute {
GLuint index;
GLint size;
GLenum type;
GLboolean normalized;
GLsizei stride;
void const *pointer;
};
public:
RenderObject(std::initializer_list<struct OGLVertexAttribute> attributes);
~RenderObject();
public:
void render();
public:
void updateIndices(std::vector<GLuint> &indices);
template<typename T>
void updateVertices(std::vector<T> &vertices);
private:
GLuint indexBuffer;
GLuint vertexArray;
GLuint vertexBuffer;
private:
unsigned int indexBufferSize;
};
我想让updateVertices
函数通用,以便它可以采用任何类型的向量(包括元组),所以我为它定义了一个模板。
template <typename T>
void RenderObject::updateVertices(std::vector<T> &vertices) {
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER,
vertices.size() * sizeof(T), &vertices[0], GL_DYNAMIC_DRAW);
}
但是,当我编译时,我得到这个链接错误:
/home/terminal/source/application.cpp:23: undefined reference to `void RenderObject::updateVertices<float>(std::vector<float, std::allocator<float> >&)'
为什么会这样,我该如何解决?
解决方案
我能给出的最佳答案通常是使用模板类,通常将实现保留在头文件中。否则,需要更多额外的东西以及更多语法才能在 .cpp 文件中实现模板化类。
另请注意,如果您这样做,则不确定某个编译器是否能够处理在 .cpp 文件中实现的模板化类。
推荐阅读
- python - 如何在嵌入式帮助命令中隐藏所有者命令 [discord.py rewrite]
- ggplot2 - 如何将线和点组合到同一个图例?
- c# - 将 HttpContext 传递给 HttpResponse.OnStarting
- php - 如何通过函数提交表单?
- python - 在 python 中获取“ImportError:没有名为 yaml 的模块”
- permissions - CodeReady 容器:开发人员无权查看拓扑
- php - PDO 获取最后使用的 CRUD 语句
- typescript - 与可选链接一起使用时,Typescript 不理解未定义的返回类型
- sql - 为表的所有列设置默认值
- python - 我如何检查每个字符串的 2 项是否不止一次出现