Skip to content
Tutorials Center
My learning

Topics

Lesson 92 of 171 ยท Templates and Generic Programming

Type Traits and Metaprogramming

Learn C++ type traits and metaprogramming - is_integral, remove_reference, conditional, writing your own traits, SFINAE with enable_if versus concepts, and std::declval.

Inside a template, you often need to ask questions about a type, or compute a new type from it. Is T an integer? Is it a pointer, and if so, to what? If T is const std::string&, what is the plain std::string underneath? Which of two types is bigger? The header <type_traits> answers all of these at compile time. Each answer is a type trait: a small class template that holds either a bool value or a resulting type.

Code that computes with types instead of values is called template metaprogramming. In this lesson you'll learn the two kinds of traits (queries and transformations), the _v and _t shortcuts, how traits are implemented with template specialization, how to write your own, and the older SFINAE technique with std::enable_if that concepts have largely replaced. You'll also meet std::declval, the trick for talking about expressions on types you can't construct.

Query traits: asking yes/no questions

A query trait has a static member value of type bool. Since C++17 every one also has a variable template ending in _v, so std::is_integral<int>::value can be written std::is_integral_v<int>.

C++ Asking questions about types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The traits fall into a few families:

Family Examples
Primary categories is_void, is_integral, is_floating_point, is_pointer, is_lvalue_reference, is_enum, is_class, is_array, is_function
Composite categories is_arithmetic, is_fundamental, is_scalar, is_object, is_reference, is_member_pointer
Properties is_const, is_signed, is_unsigned, is_abstract, is_polymorphic, is_final, is_aggregate, is_trivially_copyable, is_standard_layout, has_virtual_destructor
Operations is_constructible, is_default_constructible, is_copy_assignable, is_nothrow_move_constructible, is_invocable, is_swappable
Relationships is_same, is_base_of, is_convertible

Many of the "operations" traits matter for performance decisions. std::vector uses is_nothrow_move_constructible to decide between moving and copying on growth (see Move Semantics), and copying algorithms use is_trivially_copyable to switch to a single memmove.

Transformation traits: computing new types

A transformation trait has a nested type alias type. Since C++14 each has an alias ending in _t, so typename std::remove_reference<T>::type becomes std::remove_reference_t<T>.

Trait Turns Into
remove_reference_t<T> int&, int&& int
remove_const_t<T> const int int
remove_cvref_t<T> (C++20) const int& int
remove_pointer_t<T> int* int
add_const_t<T>, add_pointer_t<T>, add_lvalue_reference_t<T> int const int, int*, int&
decay_t<T> const int&, int[4], void(int) int, int*, void(*)(int)
make_unsigned_t<T>, make_signed_t<T> int unsigned int
underlying_type_t<E> enum class E : char char
conditional_t<B, T, F> T if B is true, else F
common_type_t<Ts...> int, double double
invoke_result_t<F, Args...> a callable and its arguments its return type

You can't print a type with std::println directly, but std::is_same_v lets you check a transformation:

C++ Transforming types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

inspect shows why remove_cvref_t matters: with a forwarding reference, T is std::string& for an lvalue, const std::string& for a const lvalue and std::string for a temporary. Comparing T directly with std::string would fail in the first two cases. Strip the reference and const first, then ask your question. This is one of the most common bugs in template code.

std::conditional_t is the compile-time ?:: both branches must be valid types, and it chooses one. Nesting it picks between several. std::to_underlying (C++23) converts an enum to its underlying integer, a shortcut for static_cast<std::underlying_type_t<E>>(e).

How traits are implemented

There's no magic in most traits. They're class templates with specializations, often built on two helpers: std::true_type and std::false_type, which are classes whose value is true or false (both are aliases of std::integral_constant<bool, B>). Here are home-made versions of three standard traits:

C++ Writing your own traits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Note how is_vector<const std::vector<int>> is false: the partial specialization matches std::vector<T, Alloc> exactly, not its const version. The standard traits behave the same way (std::is_pointer_v<int* const> is true only because is_pointer deliberately strips const first), so strip cv-qualifiers yourself when you mean "any vector".

A few traits can't be written in plain C++, such as is_enum, is_union, is_aggregate, is_trivially_copyable and underlying_type. Compilers implement them with built-in intrinsics like __is_enum(T). That's another reason to use the standard ones.

SFINAE and std::enable_if

Before C++20 there were no concepts, yet libraries still needed "this overload only for integers". They used a rule called SFINAE: Substitution Failure Is Not An Error. When the compiler substitutes deduced types into a template's signature and the result is invalid, it doesn't report an error. It just removes that template from the candidate set.

std::enable_if_t<Condition, T> exploits this. If Condition is true, it's the type T (default void); if false, it has no type member, so substitution fails and the overload disappears.

C++ SFINAE with enable_if versus concepts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The two versions do the same job, but compare readability. SFINAE has well-known problems:

  • The intent is hidden in unusual syntax: an unnamed non-type template parameter with a default, or a decltype return type.
  • Error messages talk about "no type named 'type' in enable_if" instead of the actual requirement.
  • Overloads can't be ranked: two SFINAE overloads that both survive are simply ambiguous, while concepts pick the most constrained one.
  • A failure inside the body is still a hard error; only failures in the "immediate context" (the signature) are SFINAE-friendly.

Use concepts in new code. You still need to read SFINAE, because a huge amount of existing library code (and the standard library itself, internally) uses it. The std::void_t "detection idiom" you may also see is another pre-C++20 way to ask "does this expression compile?", now replaced by requires expressions.

std::declval: expressions on types without objects

Sometimes you need the type of an expression involving a T, but you can't create a T (it may have no default constructor). std::declval<T>() (in <utility>) pretends to produce a value of type T&&. It may only appear in unevaluated contexts such as decltype, sizeof and noexcept(...); calling it for real is a compile error.

C++ std::declval in unevaluated contexts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Engine can't be constructed at all, yet you can still ask what horsepower() returns and whether it's noexcept. In C++20 code, a requires expression with parameters (requires(const T& t) { t.size(); }) covers many of declval's old jobs more readably, but declval remains the tool for computing types.

Metaprogramming in modern C++: what to use

  • Ask questions about types: std::is_*_v traits, or the standard concepts built on them, in if constexpr and requires.
  • Compute types: _t transformation traits (remove_cvref_t, conditional_t, common_type_t, invoke_result_t) and alias templates.
  • Compute values: constexpr and consteval functions (see Compile-Time Programming), not recursive templates; they're far easier to read and compile faster.
  • Restrict overloads: concepts, not enable_if.
  • Write your own trait only when the standard has nothing suitable, and give it both a _v or _t alias.

C++26 adds static reflection (^^T and std::meta), which will let code inspect members, names and enums directly. It isn't available in GCC 15's C++23 mode, so it's mentioned here only as what's coming.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Inside template <typename T> void f(T&& x), you call f(name) with a std::string name. What is std::is_same_v<T, std::string>?

    For an lvalue argument, a forwarding reference deduces T as an lvalue reference. Use std::remove_cvref_t<T> before comparing.
  2. 2. What is std::conditional_t<(sizeof(int) > 8), long, short> on a typical platform with 4-byte int?

    The condition is false, so conditional_t picks the third argument, short.
  3. 3. What does SFINAE do when substituting deduced types into a template's signature produces an invalid type?

    Substitution Failure Is Not An Error. The template just stops being a candidate; if no candidate remains, then you get a "no matching function" error.
  4. 4. Where may std::declval<T>() be used?

    declval has no definition you can run; it only pretends to produce a T&& so the compiler can work out types. Using it in evaluated code is a compile error.
  5. 5. Given template <typename T> struct is_vector : std::false_type {}; and a partial specialization for std::vector<T, A>, what is is_vector<const std::vector<int>>::value?

    const std::vector<int> does not match the pattern std::vector<T, A>, so the primary template (false_type) is used. Strip cv-qualifiers first if you mean any vector.

Summary

  • <type_traits> provides compile-time query traits (is_integral_v<T>, is_same_v<T, U>, is_nothrow_move_constructible_v<T>) and transformation traits (remove_cvref_t<T>, decay_t<T>, conditional_t<B, T, F>).
  • Use the _v and _t shortcuts; strip references and const with remove_cvref_t before comparing deduced types.
  • Traits are class templates with specializations, usually deriving from std::true_type/std::false_type; a few rely on compiler intrinsics.
  • SFINAE removes templates whose signatures fail substitution; std::enable_if uses it to restrict overloads. Concepts do the same job readably and can rank overloads.
  • std::declval<T>() lets you form expressions on a type in decltype, sizeof and noexcept without constructing it.
  • Prefer constexpr functions for compile-time values and concepts for constraints; use traits for asking about and computing types.

Next: The Standard Template Library, where containers, iterators and algorithms come together.