glUniforms()和[]运算符重载问题

glUniforms() and [] operator overloading woes

本文关键字:运算符 重载 问题 glUniforms      更新时间:2023-10-16

我在编译以下代码时遇到了一些问题:

GLint iModelMatrix = glGetUniformLocation(m_shaderProgramID, "mvMatrix");
glUniformMatrix4fv(iModelMatrix, 1, GL_FALSE, &myMatrix[0]);
GLint iLight = glGetUniformLocation(m_shaderProgramID, "vLightPos");
glUniform3fv(iLight, 1, &myVector[0]);

现在myMatrix和myVector是两个对象,每个类都重载了[]运算符,如下所示:

inline float& operator[](int index)     { return m_data[index]; }
inline float  operator[](int index) const   { return m_data[index]; }

我收到以下错误:

error C2102: '&' requires l-value

我试着理解为什么"&"是否需要左侧值?我以前传递过这样的数据。我不是简单地把地址给m_data数组的第一个索引吗?这难道不构成浮动*吗?

为什么它不满足功能规范?

void glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);

编辑:

好吧,因为我将这些对象作为const引用传递给进行上述调用的函数,所以它是按值传递float*数组,因此我不能引用它们。

我试着添加第三个操作员:

inline const float& operator[](int index) const    { return m_data[index]; }

但这让我的编译器爆炸了。我不能这样做有什么原因吗?

这:

inline float  operator[](int index) const   { return m_data[index]; }

转换为:

inline const float &operator[](int index) const   { return m_data[index]; }

如果要获取返回值的地址。您不会添加第三个版本;您当前的更改为这个。你不能取临时的地址,但你可以取const&的地址。

就我个人而言,我认为应该有一个只返回float*const float*的特殊函数,就像C++11对std::vector::data所做的那样。这样,您只需调用myMatrix.data(),而不必执行&...[0]的拼凑。它是自我记录的,显而易见。

只需将operator[]的结果存储在本地变量中

float tmp = myMatrix[0];
glUniformMatrix4fv(iModelMatrix, 1, GL_FALSE, &tmp);

这避免了无法作为l-value处理的未命名临时值。