Question

I understand they encode information about the type you instantiate them with, but how do they work? Say, for instance, the type trait std::is_class. How does it do its work? All implementations seem like empty structs, and I gotta admit I'm scratching my head.

The names seem descriptive enough, so I can understand what they mean, but what are typical scenarios that make use of type traits?

I cannot find introductory resources on the subject (or questions on SO). Pointers would be appreciated.

Was it helpful?

Solution

Some type traits, like std::is_class just use compiler intrinsics (aka built-ins). You cannot write these yourself without special support from the compiler.

Type traits are mostly useful in generic context—you may want to specialize things based on the properties of types, or impose restrictions on template arguments. For example, an implementation of std::copy may use std::memcpy internally instead of an explicit loop when the iterators are pointers to PODs. This can be achieved with SFINAE.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top