使字段功能通用

时间:2013-12-20 16:16:24

标签: 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");
}

4 个答案:

答案 0 :(得分:1)

将您的功能转换为模板很简单:

template <typename T>
void writeOutField(T *a, int length)
{
     for(int i=0; i<length; i++)
     {
         cout << a[i] << endl;
     }
}

另请参阅Function template或有关C ++的好书,其中介绍了模板,例如: The C++ Programming Language

答案 1 :(得分:1)

模板用于编写通用函数:

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

答案 2 :(得分:1)

将模板用于通用功能。这是工作代码:

#include <iostream>
#include <string>
using namespace std;

template<class T>
void writeOutField(T *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<int>(intField, 5); //Works with the non-generic version.
    writeOutField<string>(stringField, 3); //Is what I want to make work.
}

答案 3 :(得分:0)

template <class X> void writeOutField(T *a,int length) {
...
cout << a[i] << endl;
...
}