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!

Given

template <class T>
void f(T var) {
    bool advanced = policy_trait<T>::advanced;
    if ( advanced )
        cout << "Do it fancy!" << endl;
    else
        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.)