Iterators and Ranges

Using Concepts in C++

How do I use concepts in C++ to check if a type is a range?

Abstract art representing computer programming

Concepts in C++20 allow us to define requirements that types must satisfy. To determine if an object is a valid range using C++20 concepts, there are two steps:

  1. Include <ranges> Header: Standard library concepts for testing ranges are in the std::ranges namespace.
  2. Check Range Type: Use concepts like std::ranges::forward_range to determine the category.

Here's an example:

#include <vector>
#include <list>
#include <forward_list>
#include <ranges>
#include <iostream>

template <typename T>
void Log(T Range) {
  if constexpr (std::ranges::forward_range<T>) {
    std::cout << " - Forward Range\n";
  }
  if constexpr (std::ranges::bidirectional_range<T>) {
    std::cout << " - Bidirectional Range\n";
  }
  if constexpr (std::ranges::random_access_range<T>) {
    std::cout << " - Random Access Range\n";
  }
}

int main() {
  std::cout << "std::forward_list<int>:\n";
  Log(std::forward_list<int>{1, 2, 3});

  std::cout << "\nstd::list<int>:\n";
  Log(std::list<int>{1, 2, 3});

  std::cout << "\nstd::vector<int>:\n";
  Log(std::vector<int>{1, 2, 3});
}
std::forward_list<int>:
 - Forward Range

std::list<int>:
 - Forward Range
 - Bidirectional Range

std::vector<int>:
 - Forward Range
 - Bidirectional Range
 - Random Access Range

Concepts simplify template programming by providing clear requirements for types.

This Question is from the Lesson:

Iterators and Ranges

This lesson offers an in-depth look at iterators and ranges, emphasizing their roles in container traversal

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

This Question is from the Lesson:

Iterators and Ranges

This lesson offers an in-depth look at iterators and ranges, emphasizing their roles in container traversal

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:

  • 125 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