Traits and Policies

Traits are used throughout the C++ library. A trait is a class or class template that characterizes a type, possibly a template parameter. At first glance, it seems that traits obscure information, hiding types and other declarations in a morass of templates. This is true, but traits are also powerful tools used in writing templates. Traits are often used to obtain information from built-in types in the same manner as user-defined types.

A policy is a class or class template that defines an interface as a service to other classes. Traits define type interfaces, and policies define function interfaces, so they are closely related. Sometimes, a single class template implements traits and policies.

The typical application programmer might never use traits and policies directly. Indirectly, however, they are used in the string class, I/O streams, the standard containers, and iterators—just about everywhere in the standard library.

Character Traits

One of the most commonly used trait and policy templates is char_traits<> in the <string> header. The standard declares two specializations: char_traits<char> and char_traits<wchar_t>.

The rest of the C++ library uses character traits to obtain types and functions for working with characters. For example, the basic_istream class template takes a character type, charT, and a character traits type as template parameters. The default value for the traits parameter is char_traits<charT>, which is a set of character traits defined ...

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.