c++ - 使字段函数通用

标签 c++ function generics field

我已经创建了一个非通用函数来写出字段中的所有内容,但我想让它成为通用函数,以便它可以使用任何类型的字段。但是无论我在哪里看,我都对如何做到这一点感到非常困惑。 注意:我将代码翻译成英文以便更好地理解,因此如果其中任何一个是关键字,它在我的代码中并不重要。

#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/

相关文章:

c# - 如何打印通用对象的属性

c++ - 如何就地初始化数组?

sql - PL/pgSQL 函数似乎选择了错误的变量?

javascript - Protractor - X 不是函数

c - C 中参数数量未知的函数

generics - 如何初始化常量泛型数组?

generics - 只接受 Rust Generic 中的原始类型

python - 通过套接字在 python 中读取 opencv 图像

c++ - 每当动态分配内存时,您是否总是必须检查 bad_alloc?

c++ - 为什么我不能在未命名的命名空间中声明变量后在全局范围内定义它?