70

I'm reading Scott Meyers' Effective C++. He is talking about traits classes, I understood that I need them to determine the type of the object during compilation time, but I can't understand his explanation about what these classes actually do? (from technical point of view)

Cœur
  • 37,241
  • 25
  • 195
  • 267
rookie
  • 7,723
  • 15
  • 49
  • 59

2 Answers2

56

Perhaps you’re expecting some kind of magic that makes type traits work. In that case, be disappointed – there is no magic. Type traits are manually defined for each type. For example, consider iterator_traits, which provides typedefs (e.g. value_type) for iterators.

Using them, you can write

iterator_traits<vector<int>::iterator>::value_type x;
iterator_traits<int*>::value_type y;
// `x` and `y` have type int.

But to make this work, there is actually an explicit definition somewhere in the <iterator> header, which reads something like this:

template <typename T>
struct iterator_traits<T*> {
    typedef T value_type;
    // …
};

This is a partial specialization of the iterator_traits type for types of the form T*, i.e. pointers of some generic type.

In the same vein, iterator_traits are specialized for other iterators, e.g. typename vector<T>::iterator.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 5
    +1 for no magic. Even though, aren't there some traits (e.g in C++0x standard library) that can't be reliably defined using only the language, and that need special "magical" help from the compiler to work? – UncleBens Oct 20 '10 at 19:48
  • @UncleBens: I don’t know which traits C++0x defines but I’m certain that no such traits exist before C++0x. – Konrad Rudolph Oct 20 '10 at 21:41
  • 2
    Isn't *now* a kind of magic working within [`std::underlying_type`](http://en.cppreference.com/w/cpp/types/underlying_type)? – Wolf Jun 30 '14 at 08:50
  • 4
    @Wolf C++11 added a few traits which cannot be implemented on the user side, they need compiler support. And, yes, `std::underlying_type` is one of them. – Konrad Rudolph Jun 30 '14 at 08:59
  • When I read your `there is no magic`, I was wondering whether this detail would matter for this question... – Wolf Jun 30 '14 at 10:40
  • 1
    @Wolf Well the answer was written *long* before C++11 came out. – Konrad Rudolph Jun 30 '14 at 10:41
43

Traits classes do not determine the type of the object. Instead, they provide additional information about a type, typically by defining typedefs or constants inside the trait.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662