2013-04-04 64 views
0

我正在開發一個帶有C++模板的{int,short,double}多維數組的共同結構。需要關於在C++中使用結構模板的幫助

template <typename T> 
struct Array { 
    T *x; 
    int size; 
    int nDims; 
    int N[ARRAYMAXNDIMS]; 
}; 

我在聲明中沒有問題。但是,當我在函數調用中使用它時會出現問題。請幫我糾正錯誤。我在這裏附上源代碼並編譯錯誤。

非常感謝,等待您的回覆。

//============================================================================ 
// parse file parameter to memory 
#include <cmath> 
#include <cstdio> 
#include <string> 
#include <cstdlib> 

#define ARRAYMAXNDIMS 4 

using namespace std; 

// multi-dimensional integer array with at most 4 dimensions 
template <typename T> 
struct Array { 
    T *x; 
    int size; 
    int nDims; 
    int N[ARRAYMAXNDIMS]; 
}; 

template <typename T> Array<T> reduceArrayDimension(Array<T> *a); 

int main() 
{ 
    Array<int> num; 
    num.nDims = 4; 
    num.size = 16; 
    num.N[0] = 2; num.N[1] = 2; num.N[2] = 2; num.N[3] = 2; 
    num.x = (int *)calloc(num.size,sizeof(int)); 

    for (int i=0;i < num.size; i++) { 
     num.x[i] = i; 
    }; 

    Array<int> b = reduceArrayDimension(&num); 

    return 0; 
} 

template <typename T> Array<T> reduceArrayDim(Array<T> *a) { 
// reduce 4D-array to 3D-array: [0,1,2,3] -> [0,1,2] 
// B[i,j,k] = sum (A[i,j,k,l]) for all index l 

    Array<T> b; 

    b.nDims = 3; 
    int ax1 = a->N[0], ax2 = a->N[1], ax3 = a->N[2], ax4 = a->N[3]; 

    b.N[0] = ax1; b.N[1] = ax2; b.N[2] = ax3; b.N[3] = 1; 
    b.size = ax1*ax2*ax3; 
    b.x = (T *)calloc(b.size,sizeof(T)); 

    int sum = 0; 
    for (int i = 0; i < ax1; i++) 
     for (int j = 0; j < ax2; j++) 
      for (int k = 0; k < ax3; k++) { 
       sum = 0; 
       for (int l = 0; l < ax4; l++) 
        sum += a->x[i + j*ax1 + k*ax1*ax2 + l*ax1*ax2*ax3]; 
       b.x[i + j*ax1 + k*ax1*ax2] = sum; // sum over dimension 4 
      } 
    return b; 
} 

錯誤日誌:

$ g++ main1.cpp 
/tmp/ccFwJ3tA.o: In function `main': 
main1.cpp:(.text+0xba): undefined reference to `Array<int> reduceArrayDimension<int>(Array<int>*)' 
collect2: error: ld returned 1 exit status 
+1

除了名稱不匹配ForEveR spotted,另請參閱http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file。模板定義應該在使用之前。 – 2013-04-04 05:59:58

回答

2

宣言reduceArrayDimension

定義reduceArrayDim

所以,不存在reduceArrayDimension定義,這就是爲什麼有此未定義的引用。

+0

非常感謝您指出我的錯誤。現在,我可以編譯並運行它! – andycandy 2013-04-04 06:09:04