我可以基于模板参数将某个值传递给成员构造函数吗
Can I pass a certain value to member constructor based on template argument?
下面是我拥有的类模板的简化版本(它有子类):
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
,也就是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;
};
您可以执行以下操作:
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
所建议的)模板专业化。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 继承:构造函数,初始化C++11中基类的类C数组成员
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 如果基类包含双指针成员,则派生类的构造函数
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- constexpr构造函数需要常量成员函数时出现问题
- 如何在c++中定义以struct为数据成员的类中的构造函数
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 在成员构造函数之后调用基类构造函数
- C++:如何在对象构造过程中调用初始值设定项列表之外的成员构造函数
- 用作成员构造函数参数的函数的求值顺序
- 从成员构造函数(Brace Initializer vs Initializer列表)抛出异常
- 不正确的成员构造函数定义
- 我可以基于模板参数将某个值传递给成员构造函数吗
- 在类定义中调用成员构造函数
- 使用已删除的副本构造函数和初始值设定项列表重载调用类定义中的成员构造函数
- 正在从成员构造函数调用虚拟函数
- c++初始化类成员构造函数
- c++模板限制成员构造函数