加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:57:08 所属栏目:百科 来源:网络整理
导读:这是我拥有的类模板的简化版本(它有子类): templateclass Tclass Bitmap{public: typedef T pixeltype; Bitmap(const T* PixelData) : Data(/* PixelFormat enum based on T */) { ... } virtual ~Bitmap() { ... } ...protected: Texture Data;}; 模板参数
这是我拥有的类模板的简化版本(它有子类):

template<class T>
class Bitmap
{
public:
  typedef T pixeltype;
  Bitmap(const T* PixelData) : Data(/* PixelFormat enum based on T */) { ... }
  virtual ~Bitmap() { ... }
  ...
protected:
  Texture Data;
};

模板参数T到Bitmap可以是A类< X>.或A< Y> (可能在未来还有一些),其中A也是一个类模板.基于T,aka pixeltype,我需要将枚举值PixelFormatX或PixelFormatY中的一个传递给Data的构造函数,它接受一个int.

这可能吗?如果没有,我怎么能实现我所描述的?

为了完整性,这里的子类基本上是这样的:

template<class T>
class ColorizableBitmap : public Bitmap<T>
{
public:
  typedef T pixeltype;
  ColorizableBitmap(const T* PixelData) : Bitmap<T>(PixelData) { ... }
  ...
};

解决方法

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

然后使用模板专门化来定义每个类的特征:

template<>
struct BitmapTraits< A<X> >
{
    static const int PixelFormat = PixelFormatX;
};

template<>
struct BitmapTraits< A<Y> >
{
    static const int PixelFormat = PixelFormatY;
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读