gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:12:06 26 4
gpt4 key购买 nike

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

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 ,我需要传递枚举值之一 PixelFormatXPixelFormatYData 的构造函数,它需要一个 int .

这可能吗?如果没有,我该如何着手实现我所描述的内容?

为了完整起见,子类基本上是这样的:

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

最佳答案

我通常为此使用一个特征结构:

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;
};

关于c++ - 我可以根据模板参数将某个值传递给成员构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29272416/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com