c++编译时自动生成模板类

Automatic template class generation at compile time in C++

本文关键字:自动生成 编译 c++      更新时间:2023-10-16

我有一个类,称为DynamicTexture,它将纹理的widthheight作为模板参数。这些参数用于实例化一个固定大小的表(它也是一个模板类)。

在我的例子中,我将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方法是虚拟的并且派生自一个公共基类。这会比较慢,但我认为提高可读性将超过性能损失。

至于自动声明独立命名的变量,没有真正的模板解决方案。