The Simplest Possible Introduction to Traits

This is the simplest introduction to traits I could think of:

A trait is information about a type stored outside of the type.

Imagine you are making a templated algorithm, and want to use different policies for different types. If you wrote those types, you could implement the policy selection in your types directly, but this is generally not possible for built in types and types you haven’t created yourself. Traits to the rescue!


template <class T>
void f(T var) {
    bool advanced = policy_trait<T>::advanced;
    if ( advanced )
        cout << "Do it fancy!" << endl;
        cout << "KISS." << endl;

you can define policies for whatever type you want by creating template specializations of policy_trait

template <>
struct policy_trait<char> {
    static const bool advanced = false;

That’s it! :)

(The original paper on traits is Traits: a new and useful template technique by Nathan C. Myers, but An introduction to C++ Traits by Thaddaeus Frogley is probably a more intuitive introduction.)

4 thoughts on “The Simplest Possible Introduction to Traits

  1. This is kind of similar to attributes in .NET, but not quite. You can’t decorate existing types with attributes, but you can decorate references to them, so it’s almost there. Metaprogramming is fun! :)

    1. I find myself liking C++ templates more and more. Having static polymorphism that works even with built in types is really powerful.

      And the fact that the template system is Turing complete is kind of cool as well! :)

Comments are closed.