c++编译时自动生成模板类
Automatic template class generation at compile time in C++
我有一个类,称为DynamicTexture
,它将纹理的width
和height
作为模板参数。这些参数用于实例化一个固定大小的表(它也是一个模板类)。
在我的例子中,我将DynamicTexture
实例化为两个宽度/高度的各种幂(所以2x2, 4x4, 8x8, 16x16, 32x32等,一直到4096x4096)。这意味着我有很多这样的声明:
DynamicTexture<2, 2> dTexture2;
DynamicTexture<4, 4> dTexture4;
...
DynamicTexture<4096, 4096> dTexture4096;
现在的问题是,我能以某种方式自动化这个过程吗?此外,我通过查询unsigned int
类型的变量(显示用户选择的当前大小)来选择近似的dTexture,然后显示纹理:
if (currTexSize == 2) dTexture2->show();
else if (currTexSize == 4) dTexture4->show();
...
else { dTexture4096->show(); }
还是那句话,有什么方法可以避免if语句的长列表吗?
注意:我不确定如何表达这个特定问题的标题。随你怎么说
现在的问题是,我能以某种方式自动化这个过程吗?
您可以使用一些高级元编程技巧来实现:
template< int Width, int Height >
struct textures_holder
: textures_holder< Width * 2, Height * 2 >
{
typedef textures_holder< Width * 2, Height * 2 > base_t;
void show( int currTexSize ) const
{
if( currTexSize == Width ) // or is it == Height?
_texture->show();
else
base_t::show( currTexSize );
}
DynamicTexture< Width, Height > _texture;
};
template<>
struct textures_holder< 4096, 4096 >
{
void show( int currTexSize ) const
{
_texture->show();
}
};
,然后您将创建一个类型为textures_holder< 1, 1 >
的对象,并获得一个变量,每个2次幂的维度,直到4096。
您可以使用currTexSize
的以二为底的对数来索引不同纹理对象的数组,前提是它们的show
方法是虚拟的并且派生自一个公共基类。这会比较慢,但我认为提高可读性将超过性能损失。
至于自动声明独立命名的变量,没有真正的模板解决方案。
相关文章:
- 查找自动生成键并具有线性内存消耗的小型关联数组
- Qt:更新 QString 时自动生成的代码失败
- 我可以说服自动生成的构造函数将我的 POD 类成员归零吗?
- 在 C++ 中自动生成方法
- 删除了所有自动生成的构造函数/运算符的类仍然可以从函数返回吗
- 在编译时自动生成用于稀疏数组索引的switch语句
- Lamda 仅在声明为"自动"时编译,而不是在声明为'bool'时编译
- 如何在C++中自动生成运算符=?
- C++自动生成的具有常量和非常量引用的复制构造函数
- 如何使用 boost/operator.hpp 自动生成 == 运算符?
- Qt自动生成的.rc文件无法打开包含文件'windows.h'
- 阅读自动生成的 DOLFIN c++ 库文档
- 修改Mongodb源代码以禁用文档的自动生成"_id"字段
- 移动构造函数是自动生成的,即使成员没有移动构造函数?
- 如何为C++结构自动生成 python 数据解析器
- 通过 qt 对发送方和接收方使用自动生成的 Ui
- 自动在编译时如何将缩写与长期区分
- 如何使用C 根据当前时间自动生成新的CSV文件
- 自动生成的依赖项导致编译速度缓慢
- c++编译时自动生成模板类