c++ - 如何避免使用不同类型 C++ 执行相同操作的多个函数

标签 c++

我有一个用于 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/

相关文章:

c++ - 是否可以从 std::bind 对象访问参数?

C++ 错误 : no match for 'operator>>' in 'input >> Group1->Entrepreneur::Item' |

c++ - RapidXml:选择一个 first_attribute 值

c++ - 如何在 OpenGL Superbible 第 6 版中构建和运行示例?

c++ - 调用类的成员函数后的垃圾值

c++ - 在共享库的用户之间共享数据

c++ - 为什么我们不能在 Struct C++ 中使用硬编码或初始化值?

c++ - 如何通过计算新的 x 和 y 位置来围绕其中心旋转 Sprite ?

c++ - <?= 在 C++ 中是什么意思

c++ - 无法在 GCC 中使用数组