如何避免多个函数对不同类型的C++执行相同的操作
How can I avoid multiple functions which do the same thing with different types C++
我有一个C++类,它用于OpenGL缓冲区,它有许多setData()
函数来说明缓冲区可能包含的不同类型的数据,例如int:
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++只会抱怨。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- C++,系统无法执行指定的程序
- 使用C++中的模板和运算符重载执行矩阵运算
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 执行函数时导致崩溃的变量
- 无论条件是否为true,if总是在c++中执行
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 在C++中对T*类型执行std::move的意外行为
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如何在没有信号的情况下从C++执行QML插槽
- 如何确认我的constexpr表达式实际上已经在编译时执行
- C++17中的并行执行策略
- QML按钮点击功能执行顺序
- 程序在执行程序的其余部分之前退出
- 为什么catch中的代码没有被执行
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 将执行、作业和WinAPI相乘
- 对字符数组中的元素执行逐位操作
- 为什么g++在未执行的代码处标记强制转换错误
- 如何使用原子指针执行双缓冲