首页 > 解决方案 > 类内的模板方法返回一个未定义的引用

问题描述

我的标题中有这个类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> >&)'

为什么会这样,我该如何解决?

标签: c++templates

解决方案


我能给出的最佳答案通常是使用模板类,通常将实现保留在头文件中。否则,需要更多额外的东西以及更多语法才能在 .cpp 文件中实现模板化类。

另请注意,如果您这样做,则不确定某个编译器是否能够处理在 .cpp 文件中实现的模板化类。


推荐阅读