How do traits classes work and what do they do?

C++Traits

C++ Problem Overview


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++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrookieView Question on Stackoverflow
Solution 1 - C++Konrad RudolphView Answer on Stackoverflow
Solution 2 - C++fredoverflowView Answer on Stackoverflow