ProblemsTemplatesNeedle in a pack
IntermediateTemplates

Needle in a pack

Context

A variant wants to reject duplicate alternatives; a tuple-like API wants to check that the requested type is actually inside. Both reduce to the same two questions about a pack — asked and answered entirely at compile time.

Task

Two compile-time queries over a type pack: contains_v<T, Ts...> — is T among Ts; count_v<T, Ts...> — how many times. The first parameter is the needle, the rest is the haystack.

Constraints

  • contains_v<int, float, int> is true; contains_v<int> (empty haystack) is false
  • count_v<int, int, float, int> is 2; count_v<int> is 0
  • Exact type matching: const and references make types different
  • Usable in static_assert

Before you code

  • How does a fold over || answer "contains" and a fold over + answer "count"?
  • What does an empty fold over || / + evaluate to, and why is that exactly right here?
  • Why is count_v a size_t and not an int?

Tests

  • #1contains over packs
  • #2count over packs
  • #3Exact matching: const and refs differ

Hints

Hint 1

std::is_same_v<T, Ts> gives a pack of bools. Fold it with || for contains.

Hint 2

For count, a bool casts to 0 or 1 — fold the casts with +. Give the empty pack an explicit init value in the fold.

Editorpack-contains-count.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.