我有一个用于 OpenGL 缓冲区的 C++ 类,它有很多 setData()
解释缓冲区可能包含的不同类型数据的函数,例如整数:
void Buffer::setData(int* data)
{
//Bind the buffer
bind();
//Input the data into the buffer based on the type
glBufferData(type, sizeof(int) * size, data, GL_DYNAMIC_DRAW);
}
这对于函数的每个版本都是相同的,唯一改变的是 sizeof(int)
。变成 sizeof(<other type>)
我想知道是否有办法解决这个问题?我考虑的一种可能性是泛型类型变量,例如 var?我知道 var 本身在 C++ 中不存在,但有一些等价物吗?
最佳答案
模板函数可能会很好地为您服务。方法:
template< typename T > void Buffer::setData(T data)
{
//Bind the buffer
bind();
//Input the data into the buffer based on the type
glBufferData(type, sizeof(T) * size, data, GL_DYNAMIC_DRAW);
}
定义了一系列方法,每个类型 T
都有一个。当然,它可能实际上对所有类型 T
都有效,但幸运的是,C++ 只会在您使用不兼容的类型调用它时报错。
关于c++ - 如何避免使用不同类型 C++ 执行相同操作的多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25670595/