我有下面的類:添加一個構造函數模板專業化
template <typename T>
class Fixed2DContainer {
T* ptr;
public:
const int total_cols;
const int total_rows;
Fixed2DContainer(int cols, int rows);
T& operator()(int col_n, int row_n);
~Fixed2DContainer();
private : //disallow copy
Fixed2DContainer& operator=(const Fixed2DContainer&);
Fixed2DContainer operator()(const Fixed2DContainer&);
};
現在,我想專攻這個模板對於一些類,以便唯一的變化是,我可以有另一個構造。 基本上我希望能夠做到:
Fixed2DContainer<Image>("filename.jpg");
是有一種優雅的方式來做到這一點?我是相當新的模板,所以我沒有任何難度
不,你不能這樣做根本。你必須重新編寫整個班級作爲專門練習,並添加新的構造函數。您可以將大部分功能移出到主模板和專用化都使用的單獨基類中,以避免重複這一切,但大多數「功能」似乎是構造函數和複製操作,它們需要重新構建無論如何。 'ptr'和'total_cols' /'total_rows'成員可以在共同的基礎上,但是一旦您將基礎構造等添加到基礎中,您可能無法節省大量工作 –
這看起來像是一個很好的舊OO而不是模板專業化。 –