2016-01-13 63 views
-4

我有此代码类型参数:如何指定使用<>创建模板

class Grid { 
public: 
    vector<vector<int> > grid; 
    int width; 
    int height; 

    Grid (int width, int height) width(width), height(height) { 
     ... 
    } 
}; 

它使一个称为Grid类,这是整数的2D阵列。问题是,然而,目前它可以只能是整数,但我想它,所以它是一种像std::vector类中,你可以使用<>括号来选择它将存储类型。我的问题是,为了与其他任何类,以取代目前所有的int S IN 类我怎么能使用这些。

另外,你可能会说要查看它,但我试过了,我找不到任何东西,可能是因为我不知道要搜索什么,所以如果任何人可以给我一个关于这是什么,甚至称之为也会有帮助。

+3

读好[编程使用C++](http://stroustrup.com/programming.html)本书'template'-S。但教给你的答案太长。所以,你的问题太广... –

+0

没有,我的问题是,我需要做任何类型 –

+0

的'Grid'使电网在你的类定义放“模板”顶部的模板 –

回答

6

好像你只是想模板您Grid类:

template <typename T> 
class Grid { 
    public: 
    vector<vector<T> > grid; 

    // initialize the vector with the correct dimensions: 
    Grid (int width, int height) 
     : grid(width, vector<double>(height)) {} 
}; 

然后实例:

Grid<double> g(x, y); 

这将创建一个Grid对象,其中Tdouble

+0

这样的作品,谢谢! –

相关问题