Home Non-type template parameter: pass to another method
Reply: 0

Non-type template parameter: pass to another method

user1745
1#
user1745 Published in May 22, 2018, 9:20 pm

Suppose I have this generic class with a single, non-type template parameter:

template<uint8_t D>
class Tile
{
private:
    uint8_t density = D;

public:
    void someMethod()
    {
        if(D == 1)
        { /* do this */ }
        else
        { /* do that */ }
    }
};

Depending on the template parameter D, a specific code path is taken in the object's methods. The reason to do it like this, for me, is that this enables the compiler to optimize away the if statement altogether, since D never changes. To the outside world, the template parameter D doesn't change the object's interface at all - no matter what value D has, the object's interface stays the same.

Now I want to pass such an object to another method, to do something with it. How exactly would I do that in a general way?

void processSomething(Tile *tile)
{
    tile->someMethod();
}

This fails of course, since the template parameter was not specified. For the users of Tile however, the template parameter doesn't make any difference, it is for internal state only. How can I write processSomething, so that the value of the template parameter doesn't matter?

The only solutions I found were to either implement overloads like this:

void processSomething(Tile<0> *tile);
void processSomething(Tile<1> *tile);
...

which is impractical. Or to make processSomething a template itself, but then I'd have to specify the value to calls to processSomething, which only shifts the problem to the caller.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.337174 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO