Desmond Gold
Desmond Gold

Reputation: 2065

How to support range adaptors in custom container?

I have created a custom container called goldbox that only contains arithmetic types and I have also implemented begin and end member functions to iterate over the elements.

My Full Source Code:

#include <algorithm>
#include <vector>
#include <initializer_list>
#include <iostream>
#include <type_traits>
#include <ranges>

template <typename T>
concept Arithmetic = std::is_arithmetic_v<T>;

template <Arithmetic T = int>
class goldbox {
private:
    template <Arithmetic Base_t>
    struct Node {
        Base_t data;
        Node<Base_t>* prev;
        Node<Base_t>* next;
    };
    Node<T>* head;
    Node<T>* current_node;

    Node<T>*& __at_node(size_t index) {
        auto temp = head;
        size_t count {0};

        while (count < index) {
            temp = temp->next;
            count++;
        }
        current_node = temp;

        return current_node;
    }

    Node<T>*& __get_tail() {
        return __at_node(length() - 1);
    }

public:
    using value_type = T;

    goldbox() : head{nullptr}, current_node{nullptr} {}
    goldbox(std::initializer_list<T>&& list_arg) : goldbox() {
        decltype(auto) list_1 = std::forward<decltype(list_arg)>(list_arg);
        T temp[list_1.size()];
        std::copy(list_1.begin(), list_1.end(), temp);
        std::reverse(temp, temp + list_1.size());
        for (const auto& elem : temp)
            push_front(elem);
    }

    class iterator {
        private:
        Node<T>* node;
    public:
        iterator(Node<T>* arg) noexcept : node{arg} {}

        iterator& operator=(Node<T>* arg) {
            node = arg;
            return *this;
        }

        iterator operator++() {
            if (node)
                node = node->next;
            return *this;
        }

        iterator operator++(int) {
            iterator iter = *this;
            ++(*this);
            return iter;
        }

        iterator operator--() {
            if (node)
                node = node->prev;
            return *this;
        }

        iterator operator--(int) {
            iterator iter = *this;
            --(*this);
            return iter;
        }

        bool operator==(const iterator& other) {
            return (node == other.node);
        }

        bool operator!=(const iterator& other) {
            return (node != other.node);
        }

        T& operator*() {
            return node->data;
        }
    };

    iterator begin() {
        return iterator{head};
    }

    iterator end() {
        return iterator{nullptr};
    }

    size_t length() const {
        auto temp = head;
        size_t count {0};
        while (temp != nullptr) {
            ++count;
            temp = temp->next;
        }
        return count;
    }

    goldbox& push_front(T arg) {
        auto new_node = new Node<T>;

        new_node->data = arg;
        new_node->prev = nullptr;
        new_node->next = head;

        if (head != nullptr)
            head->prev = new_node;

        head = new_node;
        return *this;
    }

    goldbox& push_back(T arg) {
        auto new_node = new Node<T>;
        auto last = head;

        new_node->data = arg;
        new_node->next = nullptr;

        if (head == nullptr){
            new_node->prev = nullptr;
            head = new_node;
            return *this;
        }

        while (last->next != nullptr)
            last = last->next;
        last->next = new_node;
        new_node->prev = last;

        return *this;
    }

    goldbox& clear() {
        auto temp = head;
        Node<T>* next_temp;

        while (temp != nullptr) {
            next_temp = temp->next;
            delete temp;
            temp = next_temp;
        }

        head = nullptr;

        return *this;
    }

    goldbox& pop_back() {
        if (head != nullptr) {
            if (length() != 1) {
                delete std::move(__get_tail());
                __at_node(length() - 2)->next = nullptr;
            } else {
                this->clear();
            }
        }
        return *this;
    }

    goldbox& pop_front() {
        if (head != nullptr) {
            auto temp = head;
            head = head->next;
            delete temp;
        }
        return *this;
    }
};

int main() {
    goldbox goldbox_1 {2, 3, 5, 6, 7, 9};
    goldbox goldbox_2;

    for (const auto& elem : goldbox_1) {
        std::cout << elem << ' ';
    } std::cout << '\n';

    std::transform(goldbox_1.begin(), goldbox_1.end(), 
                   std::back_inserter(goldbox_2),
                   [](auto x){return 2 * x - 1; }
    );

    for (const auto& elem : goldbox_2) {
        std::cout << elem << ' ';
    } std::cout << '\n';

    return 0;
}

Output:

2 3 5 6 7 9
3 5 9 11 13 17

But I wanted to use it using ranges so that I don't have to create a new instance.

Once I applied the goldbox inside the range-based for loop:

for (const auto& elem: goldbox_1 | std::ranges::views::transform([](auto x){return 2 * x - 1;})) {
     std::cout << elem << ' ';
} std::cout << '\n';

It throws an error because I haven't provided an operator|.

If I used the non-pipe syntax:

for (const auto& elem: std::ranges::views::transform(goldbox_1, [](auto x){return x + 1;})) {
     std::cout << elem << ' ';
} std::cout << '\n';

It will still throw an error that both begin and end were not declared in the scope.

Upvotes: 8

Views: 1383

Answers (1)

bolov
bolov

Reputation: 75688

TLDR

Your class doesn't satisfy std::ranges::input_range because your iterator doesn't satisfy std::ranges::input_iterator. In your iterator class you need to:

  • add default constructor
  • add public difference_type alias
  • make pre increment and decrement operators return a reference
  • add difference operator
  • make operator== const
  • add public value_type alias
  • add T& operator*() const

it will still throw an error that both begin and end were not declared in the scope.

I do not know what compiler you use that gives this misleading error message. If you compile with gcc you get a proper error diagnostic:

note: the required expression 'std::ranges::__cust::begin(__t)' is invalid

  581 |         ranges::begin(__t);
      |         ~~~~~~~~~~~~~^~~~~

cc1plus: note: set '-fconcepts-diagnostics-depth=' to at least 2 for more detail

Setting a higher -fconcepts-diagnostics-depth= we can see the root causes:

note: no operand of the disjunction is satisfied

  114 |         requires is_array_v<remove_reference_t<_Tp>> || __member_begin<_Tp>
      |                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  115 |           || __adl_begin<_Tp>
      |           ^~~~~~~~~~~~~~~~~~~

Your container is not an array and you are not using adl begin but member begin so we need to look into why your class doesn't satisfy __member_begin:

note: 'std::__detail::__decay_copy(__t.begin())' does not satisfy return-type-requirement, because

  939 |           { __detail::__decay_copy(__t.begin()) } -> input_or_output_iterator;
      |             ~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~

The problem is that your iterator class is not actually a proper iterator. Lets' see why:

note: the expression 'is_constructible_v<_Tp, _Args ...> [with _Tp = goldbox::iterator; _Args = {}]' evaluated to 'false'

  139 |       = destructible<_Tp> && is_constructible_v<_Tp, _Args...>;
      |                              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The first fix is to make your iterator default constructible. Doing that then recompiling we see that your class further doesn't satisfy the concept of an iterator:

note: the required type 'std::iter_difference_t<_Iter>' is invalid, because

  601 |         typename iter_difference_t<_Iter>;
      |         ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~

and

note: '++ __i' does not satisfy return-type-requirement, because

  603 |         { ++__i } -> same_as<_Iter&>;
      |           ^~~~~

You need to add difference_type public alias and make the pre increment and pre decrement operators return a reference to the iterator.

Fixing this then recompiling we see that your class further doesn't satisfy the concept of an iterator:

note: 'std::__detail::__decay_copy(__t.end())' does not satisfy return-type-requirement, because

  136 |           { __decay_copy(__t.end()) }
      |             ~~~~~~~~~~~~^~~~~~~~~~~

error: deduced expression type does not satisfy placeholder constraints

  136 |           { __decay_copy(__t.end()) }
      |           ~~^~~~~~~~~~~~~~~~~~~~~~~~~
  137 |             -> sentinel_for<decltype(_Begin{}(std::forward<_Tp>(__t)))>;
      |             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

note: the required expression '(__t == __u)' is invalid, because

  282 |           { __t == __u } -> __boolean_testable;
      |             ~~~~^~~~~~

This means that the iterator returned by begin() is not comparable with the iterator returned by end. Looking down the diagnostic depth you can see that your operator== is not considered because it is not const.

Fixing this then recompiling we see that your class further doesn't satisfy the concept of an input_iterator:

note: the required type 'std::iter_value_t<_In>' is invalid, because

  514 |         typename iter_value_t<_In>;
      |         ~~~~~~~~~^~~~~~~~~~~~~~~~~~

This is fixed by adding a public value_type alias.

Next:

note: nested requirement 'same_as<std::iter_reference_t, std::iter_reference_t<_Tp> >' is not satisfied, because

  517 |         requires same_as<iter_reference_t<const _In>,
      |         ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  518 |                          iter_reference_t<_In>>;
      |                          ~~~~~~~~~~~~~~~~~~~~~~

This means that operator* should return the same reference type for both iterator and const iterator. This is fixed by adding a const operator*:

T& operator*();
T& operator*() const;

And now all the compile errors are fixed and both versions (pipe and non-pipe) compile. Please note I've fixed the compile errors, haven't checked your semantics.

Upvotes: 12

Related Questions