Defining Ranges using Sentinels

How Do Template Sentinels Work in C++?

How do template sentinels work in C++?

Abstract art representing computer programming

Template sentinels in C++ are a way to create sentinels that can work with any iterator type, providing greater flexibility and reusability. By defining a sentinel as a template, you can make it compatible with various containers and iterator types.

Here’s an example of a template sentinel that stops when a negative number is encountered:

#include <iostream>
#include <vector>

template <typename T>
struct Sentinel {
  bool operator==(T iter) const {
    return *iter < 0 || iter == end;
  }

  T end;
};

int main() {
  std::vector<int> numbers{1, 4, 3, 8, -2, 5};
  Sentinel<std::vector<int>::const_iterator> s{
    numbers.end()};

  for (auto it = numbers.begin(); it != s; ++it) {
    std::cout << *it << ", ";
  }
}
1, 4, 3, 8,

In this example, the Sentinel struct is defined as a template, allowing it to accept any iterator type. The operator==() method checks if the value pointed to by the iterator is negative or if the iterator has reached the end of the container.

Using template sentinels makes your code more flexible and reusable. You can apply the same sentinel logic to different types of containers and iterators without rewriting the sentinel for each specific type. This approach leverages the power of C++ templates to create versatile and efficient code.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved