Reputation: 847
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.
Upvotes: 2
Views: 290
Reputation: 66
You can write another template for the function:
template<uint8_t D>
void processSomething(Tile<D> *tile)
{
tile->someMethod();
}
Upvotes: 4
Reputation: 1844
Tile<0>
is a completely different class than Tile<1>
. You err in assuming that there is some relationship between instantiations of templates on different parameters.
The fact that you know that there is no difference in internal representation is irrelevant to the compiler. If you want polymorphic behavior, you need polymorphic classes.
Upvotes: 3