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

Can I pass a certain value to member constructor based on template argument?

本文关键字:成员 构造函数 值传 于模板 参数 我可以      更新时间:2023-10-16

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

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

模板参数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) { ... }
  ...
};

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

您可以执行以下操作:

enum A {
  x,y
};
class X {
public:
  static A a;
};
class Y {
public:
  static A a;
};
A X::a = x;
A Y::a = y;
template <class T>
class Bitmap {
public:
   Bitmap(): Data(T::a) {
   }
A Data;
};

编辑:在这种情况下,你可以做一些类似的事情:

enum A {
  x,y
};
template <const A V>
class X {
public:
  static A a;
};
template <const A V>
A X<V>::a = V;
template <class T>
class Bitmap {
public:
   Bitmap(): Data(T::a) {
   }
A Data;
};
int main() {
    Bitmap<X<x>> b;
}

编辑2:如果我不喜欢你,你现在有两个嵌套类,你仍然可以做一些类似的事情:

enum A {
  x,y
};
template <typename T>
class B {
public:
   typedef T t;
};
template <const A V>
class X {
public:
  static A a;
};
template <const A V>
A X<V>::a = V;
template <class T>
class Bitmap {
public:
   Bitmap(): Data(T::t::a) {
   }
A Data;
};
int main() {
    Bitmap<B<X<x>>> b;
}

另一种选择是(如Remy Lebeau所建议的)模板专业化。