skip to content

How do you write your own C++ trait is_sequence<T> that is true for std::vector and std::list, and why does it miss const std::vector<int>?

level: seniorimportance: should knowfreq 40%

answer

  1. primary template answers no
  2. specializations answer yes
  3. match the full template parameter list
  4. normalise in the _v helper

basics

~20 s

Declare a primary template deriving from std::false_type, add partial specializations for std::vector<T, A> and std::list<T, A> deriving from std::true_type, and provide an is_sequence_v helper. Specializations match exact types, so the helper should strip cv and references first.

solid answer

~40 s

A trait is a primary template that gives the default answer, `template <class T> struct is_sequence : std::false_type {};`, plus specializations that give the exceptions: `template <class T, class A> struct is_sequence<std::vector<T, A>> : std::true_type {};`, the same for `std::list`, and `template <class T, std::size_t N>` for `std::array`. Matching a specialization compares types exactly, so `const std::vector<int>` (or `std::vector<int>&`, which a forwarding reference deduces) matches only the primary and gets `false`. Normalise once, in the helper: `template <class T> inline constexpr bool is_sequence_v = is_sequence<std::remove_cvref_t<T>>::value;`. Name every template parameter of the container, including the allocator, or custom-allocator vectors are missed. Never add specializations to standard traits such as `std::is_integral`; the standard makes that undefined, and Apple clang 21 with libc++ rejects it.

code

cpp · 29 lines
cpp
#include <array>
#include <cstddef>
#include <iostream>
#include <list>
#include <type_traits>
#include <vector>

// Primary template: the answer for every type not matched below.
template <class T>
struct is_sequence : std::false_type {};

// Partial specializations: the answer for whole families of types.
template <class T, class A>
struct is_sequence<std::vector<T, A>> : std::true_type {};
template <class T, class A>
struct is_sequence<std::list<T, A>> : std::true_type {};
template <class T, std::size_t N>
struct is_sequence<std::array<T, N>> : std::true_type {};

// One helper normalises the query: strip references and cv first (C++20).
template <class T>
inline constexpr bool is_sequence_v = is_sequence<std::remove_cvref_t<T>>::value;

int main() {
    std::cout << is_sequence<const std::vector<int>>::value   // 0: no specialization matches
              << is_sequence_v<const std::vector<int>&>      // 1
              << is_sequence_v<std::array<char, 4>>          // 1
              << is_sequence_v<int> << '\n';                  // 0
}

go deeper

for a junior

Recognise the pattern: a false_type primary template plus true_type specializations for the types that should answer yes.

for a middle

Write such a trait for vector and list, add the _v helper, and explain why qualified or reference types fall back to the primary template.

for a senior

Cover allocator and non-type parameters, normalise in one helper, and know that specializing standard traits is undefined while specializing your own is a customization point.

for a principal

Decide which traits a library exposes as customization points, and what default answer is safe when a type is unknown.

## Anatomy of a hand-written trait The serializer needs to know whether a type is a sequence container it can write element by element. No standard trait answers that, so the library writes one: 1. A **primary template** that gives the default answer for every type: `template <class T> struct is_sequence : std::false_type {};`. 2. **Partial specializations** that give the answer for whole families of types: `template <class T, class A> struct is_sequence<std::vector<T, A>> : std::true_type {};`. 3. A **variable template helper** in the `_v` style that callers actually use, and that normalises the query. Deriving from `std::true_type` and `std::false_type` (or `std::bool_constant<B>`, C++17) gives the trait the same interface as the standard ones: `::value`, a conversion to `bool`, and a distinct type usable for tag dispatch. ```cpp template <class T> struct is_sequence : std::false_type {}; template <class T, class A> struct is_sequence<std::vector<T, A>> : std::true_type {}; template <class T, class A> struct is_sequence<std::list<T, A>> : std::true_type {}; template <class T, std::size_t N> struct is_sequence<std::array<T, N>> : std::true_type {}; template <class T> inline constexpr bool is_sequence_v = is_sequence<std::remove_cvref_t<T>>::value; ``` ## Why const std::vector<int> is missed A partial specialization is used only if its argument list can be **deduced to match** the requested arguments exactly. `std::vector<T, A>` can match `std::vector<int, std::allocator<int>>`, but `const std::vector<int>` is a different type: the `const` sits outside the template-id, and nothing in `std::vector<T, A>` can absorb it. The same holds for `std::vector<int>&`, which is what `T` becomes when a forwarding-reference parameter receives an lvalue. All of these fall back to the primary template and answer `false`. There are two ways to fix it: - **normalise in the helper**, as above, so `is_sequence_v<const std::vector<int>&>` asks about `std::vector<int>`; - or add more specializations for `const`, `volatile` and reference forms, which quickly multiplies. The helper is the better place: one line, and every caller gets the same answer. The class template `is_sequence<T>` stays exact, which is how the standard traits behave too (`std::is_enum_v<const Kind&>` is `false`). ## Match the container's full parameter list `std::vector` has two template parameters, the element type and the allocator. A specialization written as `is_sequence<std::vector<T>>` matches only `std::vector<T, std::allocator<T>>`, because the default argument is filled in when the specialization is declared. A vector with a custom allocator, including `std::pmr::vector<T>`, is then reported as not a sequence. Name every parameter: `template <class T, class A>`. For `std::array`, the second parameter is a value, `std::size_t N`, so the specialization uses a non-type template parameter. ## Do not specialize standard traits It is tempting to extend `std::is_integral` for a `BigInt`. The standard forbids it: unless a trait says otherwise, the behaviour of a program that adds specializations for any of the templates in `<type_traits>` is **undefined**. Library code relies on those traits meaning exactly what the standard says. Apple clang 21 with libc++ turns this into an error: `'is_integral' cannot be specialized: Users are not allowed to specialize this standard library entity [-Winvalid-specialization]`. Your **own** traits are different: specializing them is how users extend your library. Document `is_sequence` as a customization point, and a team with a ring buffer can write `template <class T> struct is_sequence<ring_buffer<T>> : std::true_type {};` in their own code. ## Testing the trait A trait is cheap to test exhaustively with `static_assert`, and the tests document its contract: ```cpp static_assert(is_sequence_v<std::vector<int>> && is_sequence_v<std::list<char>>); static_assert(is_sequence_v<const std::vector<int>&>); // normalised static_assert(is_sequence_v<std::pmr::vector<int>>); // other allocator static_assert(!is_sequence_v<int> && !is_sequence_v<std::string>); ``` ## Design checklist - Give the primary template the **safe default**, usually `false`, so unknown types take the conservative path. - Inherit from `std::bool_constant` rather than declaring a bare `static constexpr bool`, so the trait works for tag dispatch. - Keep the class template **exact** and normalise in the `_v` helper. - Specialize on the **full** parameter list of each container template. - Pair the trait with a `static_assert` at the point of use, so an unsupported type fails with a message rather than a deep error. | Question | Tool | |---|---| | is `T` one of a known family of templates? | a hand-written trait with partial specializations | | does `T` support some operation? | a detection idiom or a C++20 requires-expression | | a fixed property of built-in types | a standard trait such as `std::is_enum` |

  • How should is_sequence handle std::array, whose second template parameter is a size?
    With a specialization whose second parameter is a non-type template parameter: `template <class T, std::size_t N> struct is_sequence<std::array<T, N>> : std::true_type {};`. A pattern written as `template <class T, class A>` cannot match `std::array`, because its second argument is a value, not a type.
  • How do users opt their own containers into your trait?
    By specializing your trait for their type, which is allowed because it is your template, not the standard library's. Document the trait as a customization point, keep the primary template's default conservative, and make sure the `_v` helper normalises cv and references so a user's single specialization covers `const` and reference uses as well.

  • A specialization for std::vector<T> also matches const std::vector<T>.
  • Specializing std::is_integral is the idiomatic way to extend it.
  • is_sequence<std::vector<T>> matches vectors with any allocator.
  • A trait's specializations are chosen at run time from the object's type.
  • A trait needs SFINAE; plain specializations cannot express 'is a vector'.

Assumes C++20 for std::remove_cvref_t in the helper; C++17 code composes std::remove_cv_t and std::remove_reference_t.