Recently while working on a project involving computational algebra using C++, I encountered a need of mapping a data-structures to algorithms in a one-to-one way. To be concrete, my algorithm’s (call it
doGreatThings()) implementation needed to be aware of the type of the data-structure which was being used inside one of the arguments passed to my algorithm. The implementation of
doGreatThings() would need to be very different depending upon the type of data-structure being used. I had sever data-structures and corresponding implementations of
doGreatThings() and I needed a clean way to let the algorithm know which data-structure was being used at the compile-time. Enter trait classes!
As put succinctly by the master himself,
Think of a trait as a small object whose main purpose is to carry information used by another object or algorithm to determine "policy" or "implementation details". - Bjarne Stroustrup
Traits can be used to introspect a type and provide implementation of a functionallity based on the type or impose a constraint on the type.
Trait classes are not a construct provided by the language but an idiom/pattern developed by programmers. It uses two very useful techniques of template metaprogramming which are worth remembering. The first one is “use types to pass information at compile-time” and the second one is “use function overloading as
if-else statement at compile-time”