2013-04-04 69 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