开发者

Automatic template class generation at compile time in C++

开发者 https://www.devze.com 2023-04-12 09:44 出处:网络
I have a class, called DynamicTexture that takes in the width and height of a texture as template parameters. The parameters are used to instantiate a fixed size table (which is also a template class)

I have a class, called DynamicTexture that takes in the width and height of a texture as template parameters. The parameters are used to instantiate a fixed size table (which is also a template class).

In my case, I am instantiating the DynamicTexture for various powers of two width/height (so 2x2, 4x4, 8x8, 16x16, 32x32 etc. all the way to 4096x4096). That means I have a lot of declarations like this:

DynamicTexture<2, 2>       dTexture2;
DynamicTexture<4, 4>       dTexture4;
...
DynamicTexture<4096, 4096> dTexture4096;

Now the question is, can I automate that process somehow? Furthermore, I am selecting the approxiate dTexture by quering a variable of type unsigned int (which shows the current size selected by the user) and then displaying the texture:

if (currTexSize == 2) dTexture2->show();
else i开发者_运维知识库f (currTexSize == 4) dTexture4->show();
...
else { dTexture4096->show(); }

Again, any way to avoid the long list of if statements?

NOTE: I am not sure how to phrase the title for this particular question. Feel free to re-word it.


Now the question is, can I automate that process somehow?

You can do it with some advanced metaprogramming tricks:

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

then you would create an object of type textures_holder< 1, 1 > and get a variable for each of the power of 2 dimensions up to 4096.


You can use the base-two logarithm of currTexSize to index into an array of different texture objects, provided their show method is virtual and derived from a common base class. This will be slower, but I think the improved readability will outdo the performance loss.

As for automatically declaring independently-named variables, there is no real template solution for this.

0

精彩评论

暂无评论...
验证码 换一张
取 消