Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do traits classes work and what do they do?

Tags:

c++

traits

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)

like image 943
rookie Avatar asked Oct 20 '10 15:10

rookie


People also ask

What is a trait class?

What is a trait ? In PHP, a trait is a way to enable developers to reuse methods of independent classes that exist in different inheritance hierarchies. Simply put, traits allow you to create desirable methods in a class setting, using the trait keyword. You can then inherit this class through the use keyword.

What are class traits in sociology?

Class traits, also called class markers, are the typical behaviors, customs, and norms that define each class. Class traits indicate the level of exposure a person has to a wide range of cultures.

How do you use traits?

To use a trait in a class, you use the use keyword. All the trait's methods are available in the class where it is used. Calling a method of a trait is similar to calling an instance method. Both BankAccount and User classes reuse methods of the Logger trait, which is very flexible.

What is a trait class C++?

Think of a trait as a small object whose main purpose is to carry information used by another object or algorithm to determine "policy" or "implementation details". - Bjarne Stroustrup. Both C and C++ programmers should be familiar with limits. h , and float.


1 Answers

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.

like image 174
Konrad Rudolph Avatar answered Oct 14 '22 20:10

Konrad Rudolph