2013-12-20 40 views
0

我做了一個非泛型函數來寫出字段中的所有內容,但我想使它通用,因此它可以使用任何類型的字段。但在我看來,我對如何做到這一點感到非常困惑。 注意:爲了更好的理解,我將代碼翻譯成英文,所以如果其中任何一個是關鍵字,那麼在我的代碼中並不重要。製作一個字段函數generic

#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"); 
} 
+0

通過泛型,你的意思是模板? – user1781290

+0

'writeOutField(stringField,3);' – deW1

回答

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 
+0

這正是我所要找的,謝謝。 – Danieboy

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

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

解釋代碼會很有幫助 –

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. 
} 
相關問題