这是我拥有的类模板的简化版本(它有子类):
template<class T>
class Bitmap
{
public:
typedef T pixeltype;
Bitmap(const T* PixelData) : Data(/* PixelFormat enum based on T */) { ... }
virtual ~Bitmap() { ... }
...
protected:
Texture Data;
};
Run Code Online (Sandbox Code Playgroud)
模板参数T来Bitmap可以是类A<X>或A<Y>(可能多了一些在未来),这里A是一个类模板中.基于T,又名pixeltype,我需要传递一个枚举值PixelFormatX或PixelFormatY构造函数Data,它需要一个int.
这可能吗?如果没有,我怎么能实现我所描述的?
为了完整性,这里的子类基本上是这样的:
template<class T>
class ColorizableBitmap : public Bitmap<T>
{
public:
typedef T pixeltype;
ColorizableBitmap(const T* PixelData) : Bitmap<T>(PixelData) { ... }
...
};
Run Code Online (Sandbox Code Playgroud)
我通常使用traits结构:
template<class T>
struct BitmapTraits
{
};
template<class T, class traits = BitmapTraits<T> >
class Bitmap
{
public:
typedef T pixeltype;
Bitmap(const T* PixelData) : Data(traits::PixelFormat) { ... }
virtual ~Bitmap() { ... }
...
protected:
Texture Data;
};
Run Code Online (Sandbox Code Playgroud)
然后使用模板专门化来定义每个类的特征:
template<>
struct BitmapTraits< A<X> >
{
static const int PixelFormat = PixelFormatX;
};
template<>
struct BitmapTraits< A<Y> >
{
static const int PixelFormat = PixelFormatY;
};
Run Code Online (Sandbox Code Playgroud)