How to use concepts with custom ranges in C++?
How can I use concepts to ensure my custom type is a valid range in C++?
Using concepts with custom ranges in C++ allows you to enforce constraints at compile time, ensuring your custom type meets the criteria of a range.
Concepts from the <ranges>
header can be used to assert properties like random_access_range
and contiguous_range
. Here's how:
#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
Using static_assert
with concepts ensures that your custom type Party
remains a valid range, and any violations will be caught at compile time.
Implementing Ranges for Custom Types
Learn to implement iterators in custom types, and make them compatible with range-based techniques.