如何使用模板在CPP中分配3D数组

时间:2014-08-06 07:23:23

标签: c++

我想编写一个模板类,用于为任何类型的变量分配3D数组。以下代码是我尝试过的:

class Alloc3D{
public:
    template <class T>
    static T*** Alloc(int w, int h, int d);
};

template <class T>
T*** Alloc(int w, int h, int d)
{
    T *** field = new T **[w+1];
    for( int i=0; i<w; i++ ) { 
        field[i] = new T*[h+1];
        for( int j=0; j<h; j++ ) { 
            field[i][j] = new T[d];
        }
        field[i][h] = NULL;
    }   
    field[w] = NULL;    
    return field;
}

然而,当我将此函数称为:

int*** k = Alloc3D::Alloc<int>(nX_, nY_, nZ_);

它没有用。

我的问题是我不能使用这种风格为任何类型的变量分配3D数组吗?如果我只使用函数而不是类,模板将正常工作。

3 个答案:

答案 0 :(得分:1)

定义Alloc函数时缺少类名:

声明:

template <class T>
static T*** Alloc(int w, int h, int d);

定义:

template <class T>
T*** Alloc3D::Alloc(int w, int h, int d) {}

答案 1 :(得分:0)

这是因为您只声明 Alloc3d::Alloc函数。您定义了全局函数Alloc

答案 2 :(得分:0)

虽然这不是您的问题的解决方案,但我想为您想要做的事情提出另一个实现:

template<typename Ty>
class Grid3D
{
public:
    Grid3D(int w, int h, int d)
    : w_(w), h_(h), d_(d), p_(w*h), cells_(w*h*d)
    {
    }

    Ty& at(int x, int y, int z) { return cells_[p_*z + w_*y + x]; }
    const Ty& at(int x, int y, int z) const { return cells_[p_*z + w_*h + x]; }

private:
    typename std::vector<Ty> cells_;
    int w_, h_, d_, p_;
};

int main(int argc, char* argv[])
{
    Grid3D<float> g(4, 5, 6);
    g.at(2, 3, 4) = 3.14159f;
    // ...
}