A blog on various topics in C++ programming including language features, standards, idioms, design patterns, functional, and OO programming.

Tuesday, April 25, 2006

C++ templates should define traits

Exposing type information "out" from a class template appears to me as a good practice. For example, a class template Array<T> should define a trait which looks something like typedef T Array:TYPE in its public interface. Not only the parameter type, it should also expose any composite types used inside the template.

There are several good reasons behind it.

1. Member functions of the class can make use of the traits. 2. You can avoid typing really long names using these quick typedefs.3. Consistency.4. Other classes can make use of the traits. For example, derived classes. Sometimes it is simply not possible to write a non-template derived class of a parameterized class if the parameterized base-class does not expose necessary traits.