11

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.

Kristian D'Amato
  • 3,996
  • 9
  • 45
  • 69
  • They could be implemented by the compiler (even though they look like regular class template definitions). However, I think a possible implementation of `is_class` is described in Alexandrescu's "Modern C++ Design" – Andy Prowl Dec 22 '13 at 22:42
  • 1
    Related: http://stackoverflow.com/q/20181702/420683 – dyp Dec 22 '13 at 22:55

1 Answers1

7

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.