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.)

Posted in C++. Tags: , . 4 Comments »

4 Responses to “The Simplest Possible Introduction to Traits”

  1. Asbjørn Ulsberg Says:

    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! :)

    • Anders Schau Knatten Says:

      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! :)

  2. Anders Schau Knatten Says:

    Due to a high amount of spam, this article has been closed for comments.


Comments are closed.

%d bloggers like this: