OpenGL学习中std::vector::push_back出现E0304重载不匹配错误求助
OpenGL E0304错误:std::vector::push_back参数不匹配问题
我正在跟随OpenGL系列教程学习,在视频约13:00处,代码中的push_back函数抛出E0304错误,无法定位自身代码与教程的差异。
错误信息
Error (active) E0304 no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=VertexBufferElement, _Alloc=std::allocator<VertexBufferElement>]" matches the argument list TheChernoOpenGl C:\Users\Hunter Martenson\source\repos\TheChernoOpenGl\TheChernoOpenGl\src\VertexBufferLayout.h 31
我的代码
#pragma once #include <vector> #include <GL/glew.h> struct VertexBufferElement { unsigned int type; unsigned int count; bool normalized; }; class VertexBufferLayout { private: std::vector<VertexBufferElement> m_Elements; unsigned int m_Stride; public: VertexBufferLayout () : m_Stride(0) {} template<typename T> void Push (int count) { static_assert(false); } template<> void Push<float> (int count) { m_Elements.push_back({ GL_FLOAT, count, false }); m_Stride += sizeof(GLfloat); } template<> void Push<unsigned int> (int count) { m_Elements.push_back ({GL_UNSIGNED_INT, count, false }); m_Stride += sizeof (GLuint); } template<> void Push<unsigned char> (int count) { m_Elements.push_back ({GL_UNSIGNED_BYTE, count, true }); m_Stride += sizeof (GLbyte); } inline const std::vector<VertexBufferElement> GetElements () const { return m_Elements; } inline unsigned int GetStride () const { return m_Stride; } };
问题分析与解决
这个错误核心原因是编译器未启用C++11及以上标准,导致无法识别你使用的结构体聚合初始化语法。{ GL_FLOAT, count, false }这种直接初始化结构体的方式是C11引入的特性,若编译器默认使用C98标准,就会因无法解析该语法,导致push_back找不到匹配的重载。
两种解决途径:
开启C++11或更高版本标准
在Visual Studio中操作:右键项目 → 属性 → 配置属性 → C/C++ → 语言 → C标准,选择ISO C++11 标准(/std:c++11)或更高版本(如C17)。给结构体添加显式构造函数
若不想修改编译器设置,可给VertexBufferElement添加构造函数替代聚合初始化:struct VertexBufferElement { unsigned int type; unsigned int count; bool normalized; VertexBufferElement(unsigned int t, unsigned int c, bool n) : type(t), count(c), normalized(n) {} };对应的
push_back调用改为:m_Elements.push_back(VertexBufferElement(GL_FLOAT, count, false));
另外注意一个细节:Push<unsigned char>实现中,sizeof(GLbyte)对应有符号字节类型,而你传入的type是GL_UNSIGNED_BYTE,建议改为sizeof(GLubyte)保证类型匹配。
内容的提问来源于stack exchange,提问作者Hunter Martenson
相关产品推荐
相关产品推荐

