我已经创建了一个非通用函数来写出字段中的所有内容,但我想让它成为通用函数,以便它可以使用任何类型的字段。但是无论我在哪里看,我都对如何做到这一点感到非常困惑。 注意:我将代码翻译成英文以便更好地理解,因此如果其中任何一个是关键字,它在我的代码中并不重要。
#include <iostream>
#include <string>
using namespace std;
void writeOutField(int *a, int length)
{
for(int i=0; i<length; i++)
{
cout << a[i] << endl;
}
}
int main()
{
int intField[6] = {9, 7, 5, 3, 1};
string stringField[4] = {"Kalle", "Eva", "Nisse"};
writeOutField(intField, 5); //Works with the non-generic version.
writeOutField(stringField, 3); //Is what I want to make work.
system("pause");
}
最佳答案
模板用于编写泛型函数:
template <typename T>
void writeOutField(T const *a, int length) // const is optional, but a good idea
{
// your function body here
}
可以为具有合适 <<
的任何类型调用此函数过载。
writeOutField(intField, 5); // Works: int is streamable
writeOutField(stringField, 3); // Works: string is also streamable
关于c++ - 使字段函数通用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20707714/