Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <string>
- template <typename Derived>
- struct Iterable {
- public:
- Derived& Myself() {
- return static_cast<Derived&>(*this);
- }
- const Derived& Myself() const {
- return static_cast<const Derived&>(*this);
- }
- size_t Size() const {
- return std::distance(Myself().Begin(), Myself().End());
- }
- auto& Front() {
- return *Myself().Begin();
- }
- auto& Back() {
- return *std::prev(Myself().End());
- }
- auto& operator[](size_t i) {
- return Myself().Begin()[i];
- }
- const auto& operator[](size_t i) const {
- return Myself().Begin()[i];
- }
- };
- template <typename Derived>
- struct Comparable {
- Derived& Myself() {
- return static_cast<Derived&>(*this);
- }
- const Derived& Myself() const {
- return static_cast<const Derived&>(*this);
- }
- bool operator>(const Derived& rhs) const {
- return rhs < Myself();
- }
- bool operator>=(const Derived& rhs) const {
- return !(Myself() < rhs);
- }
- bool operator<=(const Derived& rhs) const {
- return !(rhs < Myself());
- }
- bool operator==(const Derived& rhs) const {
- return !(Myself() < rhs) && !(rhs < Myself());
- }
- };
- struct String : public Comparable<String>, public Iterable<String> {
- std::string value; // oversimplified for demonstrative purposes
- String(std::string s) : value(std::move(s)) {}
- bool operator<(const String& rhs) const {
- std::cout << "Called <\n";
- return value < rhs.value;
- }
- // If it doesn't exist, base class implementation is called
- // bool operator==(const String& rhs) const {
- // std::cout << "Called ==\n";
- // return value == rhs.value;
- // }
- auto Begin() {
- return value.begin();
- }
- auto Begin() const {
- return value.begin();
- }
- auto End() {
- return value.end();
- }
- auto End() const {
- return value.end();
- }
- };
- void Compilable() {
- String a{"abc"};
- const String b{"axyz"};
- a < b;
- a > b;
- a == b;
- a <= b;
- a >= b;
- a[1] = 'a';
- // b[1] = 'a';
- b.Size();
- }
- int main() {
- String a{"abc"};
- const String b{"axyz"};
- a == b;
- std::cout << b[1] << "\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement