Top of document
©Copyright 1999 Rogue Wave Software

Chapter 17: The Traits Parameter

Consider the following problem. You have a matrix that must work for all types of numbers, but the behavior of the matrix depends, in at least some measure, on the type of number. This means your matrix can't handle all numbers in the same way.

Except for the behavioral difference, it sounds like the perfect problem for a template. But you can't hang extra information on the number type because it's often just a built-in type, so you can't use a single template. The template will do the same thing for every number type, which is just what we can't do in this case. You could specialize, but then you have to re-implement the entire matrix class for every type of number. It may well be that most of the class is the same. Worse yet, if you want to leave your interface open for use with some unknown future type, you're requiring that future user to reimplement the entire class as well.

What you really want is to put everything that doesn't change in one place, and repeatedly specify only the small part that does change with the type. The technique for doing this is generally referred to as using a traits parameter.


Top of document