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

How can I avoid multiple functions which do the same thing with different types C++

本文关键字:C++ 执行 操作 同类型 何避免 函数      更新时间:2023-10-16

我有一个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++只会抱怨。