C++ Tag Dispatch | Compile-Time Algorithm Selection (Iterators and Traits)
이 글의 핵심
Tag dispatch selects the best `*_impl` overload at compile time using iterator categories or custom tag hierarchies.
What is tag dispatch? Why use it?
Problem: iterator-specific optimizations
std::advance should use pointer arithmetic for random-access iterators but step iterators for weaker categories.
Solution: pass a tag object
Use std::iterator_traits<Iter>::iterator_category{} to pick an overload of advance_impl.
flowchart TD
start["my_advance(it, n)"]
traits["iterator_traits::iterator_category"]
tag1["random_access_iterator_tag"]
tag2["bidirectional_iterator_tag"]
impl1["advance_impl(..., random_access)\n it += n O(1)"]
impl2["advance_impl(..., bidirectional)\n step loop O(n)"]
start --> traits
traits --> tag1
traits --> tag2
tag1 --> impl1
tag2 --> impl2
The article continues with minimal tag dispatch, std::distance-style examples, type-trait tags (signed/unsigned), SFINAE comparison, iterator hierarchy pitfalls, production patterns (multi-level tags, concepts + tags), and a container insert example with reserve for random-access iterator ranges.
Summary
| Concept | Meaning |
|---|---|
| Tag dispatch | Select overloads via empty tag parameters |
| Purpose | Compile-time algorithm selection |
| Pros | Often clearer than nested enable_if |
| Cons | Requires tag design; still templates |
FAQ
Resources: C++ Templates: The Complete Guide, Effective STL, cppreference iterator tags.
Related posts
- SFINAE
- Type traits
- CRTP
Keywords
C++, tag dispatch, templates, metaprogramming, STL, iterator.
See also
- Tag dispatching
enable_if- Iterator invalidation
- Iterator guide
- SFINAE