Implementing Ranges for Custom Types

How do I assert a type is a range in C++?

How can I ensure my custom type is a valid range in C++?

Abstract art representing computer programming

To ensure your custom type is a valid range, you can use static_assert along with concepts from the <ranges> header in C++20.

This allows you to check that your type meets the criteria for being a range. Here's how you can assert that a type is a random access range and a contiguous range:

#include <vector>
#include <ranges>
#include <string>

class Player {
public:
  Player(std::string Name) : mName(Name) {}
  std::string GetName() const { return mName; }
private:
  std::string mName;
};

class Party {
public:
  void AddMember(const std::string& NewMember) {
    PartyMembers.emplace_back(NewMember);
  }

  auto begin() {
    return PartyMembers.begin();
  }
  
  auto end() {
    return PartyMembers.end();
  }

private:
  std::vector<Player> PartyMembers;
};

static_assert(std::ranges::random_access_range<Party>);
static_assert(std::ranges::contiguous_range<Party>);

int main() {
  Party MyParty;
  MyParty.AddMember("Legolas");
  MyParty.AddMember("Gimli");
  MyParty.AddMember("Frodo");

  for (const auto& Player : MyParty) {
    std::cout << Player.GetName() << '\n';
  }
}
Legolas
Gimli
Frodo

This ensures that if any future changes to Party violate the range requirements, you'll be alerted during compilation.

This Question is from the Lesson:

Implementing Ranges for Custom Types

Learn to implement iterators in custom types, and make them compatible with range-based techniques.

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

This Question is from the Lesson:

Implementing Ranges for Custom Types

Learn to implement iterators in custom types, and make them compatible with range-based techniques.

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