我可以根据模板参数将某个值传递给成员构造函数吗?

eml*_*lai 3 c++ templates

这是我拥有的类模板的简化版本(它有子类):

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)

模板参数TBitmap可以是类A<X>A<Y>(可能多了一些在未来),这里A是一个类模板中.基于T,又名pixeltype,我需要传递一个枚举值PixelFormatXPixelFormatY构造函数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)

Rem*_*eau 5

我通常使用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)