Beyond the basics
A lot can be accomplished using the template features we've examined so far. In this section, we're going to see how to make our templates more powerful, through features that are easy to learn and use. We'll start with template specializations.
Template specializations
All instantiations of a template get the same implementation of the template body. Parameters may be substituted in different places, but the overall implementation doesn't change. However, there are times when it's useful for a template to behave differently when instantiated with different types. Simple cases, where one or two lines are different for one or two types, are easy to configure at compile time with static if
, but sometimes the code is hard to read. In more complex cases, such as when different types require completely different implementations, static if
is not practical.
Template specializations allow us to implement multiple versions of the same template for different types. Earlier, we implemented...