C++ 如何在自定义容器中支持范围适配器?

C++ 如何在自定义容器中支持范围适配器?,c++,c++20,std-ranges,C++,C++20,Std Ranges,我创建了一个名为goldbox的自定义容器,它只包含算术类型,并且还实现了begin和end成员函数来迭代元素 我的完整源代码: #include <algorithm> #include <vector> #include <initializer_list> #include <iostream> #include <type_traits> #include <ranges> template <typenam

我创建了一个名为
goldbox
的自定义容器,它只包含算术类型,并且还实现了
begin
end
成员函数来迭代元素

我的完整源代码:

#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;
}
但我想使用范围来使用它,这样就不必创建新实例

一旦我在基于范围的for循环中应用了
goldbox

for (const auto& elem: goldbox_1 | std::ranges::views::transform([](auto x){return 2 * x - 1;})) {
     std::cout << elem << ' ';
} std::cout << '\n';
它仍然会抛出一个错误,即
begin
end
未在作用域中声明。

TLDR

您的类不满足
std::ranges::input\u range
,因为您的迭代器不满足
std::ranges::input\u迭代器
。在迭代器类中,您需要:

  • 添加默认构造函数
  • 添加公共
    差异\u类型
    别名
  • 使预递增和递减运算符返回一个引用
  • 加法差分算子
  • 使
    运算符==
    常量
  • 添加公共
    值\u类型
    别名
  • 添加
    T&operator*()const

它仍然会抛出一个错误,即begin和end都没有在作用域中声明

我不知道您使用的是什么编译器,它给出了这种误导性的错误信息。如果使用gcc编译,则会得到正确的错误诊断:

注意:所需的表达式“std::ranges::_cust::begin(_t)”为 无效的

cc1plus:注意:将“-fconcepts diagnostics depth=”设置为至少2以了解更多详细信息

设置更高的
-fconcepts diagnostics depth=
我们可以看到根本原因:

注意:不满足析取操作数

  114 |         requires is_array_v<remove_reference_t<_Tp>> || __member_begin<_Tp>
      |                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  115 |           || __adl_begin<_Tp>
      |           ^~~~~~~~~~~~~~~~~~~
问题是迭代器类实际上不是一个合适的迭代器。让我们看看原因:

注:表达式“是可构造的”[with _Tp= goldbox::iterator;_Args={}]'计算为'false'

  139 |       = destructible<_Tp> && is_constructible_v<_Tp, _Args...>;
      |                              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
错误:推导的表达式类型不满足占位符 约束条件

  136 |           { __decay_copy(__t.end()) }
      |           ~~^~~~~~~~~~~~~~~~~~~~~~~~~
  137 |             -> sentinel_for<decltype(_Begin{}(std::forward<_Tp>(__t)))>;
      |             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
这意味着
begin()
返回的迭代器与
end
返回的迭代器不可比较。向下查看诊断深度,您可以看到您的
运算符==
未被考虑,因为它不是常量

修复此问题,然后重新编译,我们发现您的类进一步不满足输入迭代器的概念:

注意:所需类型“std::iter_value_t”无效,因为

  282 |           { __t == __u } -> __boolean_testable;
      |             ~~~~^~~~~~
  514 |         typename iter_value_t<_In>;
      |         ~~~~~~~~~^~~~~~~~~~~~~~~~~~
  517 |         requires same_as<iter_reference_t<const _In>,
      |         ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  518 |                          iter_reference_t<_In>>;
      |                          ~~~~~~~~~~~~~~~~~~~~~~
这意味着
操作符*
应该为
迭代器
常量迭代器
返回相同的引用类型。通过添加常量
运算符*
,可以解决此问题:

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

现在所有的编译错误都被修复了,两个版本(管道和非管道)都可以编译。请注意,我已经修复了编译错误,还没有检查您的语义。

我对您制作自己的容器的原因有点好奇?虽然这样做几次可能是一个很好的练习,但大多数情况下,标准容器应该足以满足大多数情况。是的,我复制了标准容器的用法,例如双链接列表,但这并不意味着我将在项目中应用它,而只是作为练习。至于你的问题,如果迭代器是正确的,你就不需要做任何事情。任何iterable容器(带有
begin
end
成员函数和正确实现的迭代器)都可以按原样使用。请尝试创建一个来向我们展示,并在问题中包含完整的生成输出。保留以双下划线开头的标识符。请不要添加更新来解决您最初提出的问题,因为这样会使现有答案无效。如果您有解决方案,请继续添加答案。如果你有新的问题,而这些问题并没有被现有的答案解决,那就继续写一个新的问题吧。我很难重新检查我源代码中的错误。当你把你的答案总结出来,我就放心了,现在它终于编译出来了,没有任何错误。非常感谢你!您不需要定义
运算符-
,只需定义一个成员
差分类型
@t.C.谢谢。编辑。
  603 |         { ++__i } -> same_as<_Iter&>;
      |           ^~~~~
  136 |           { __decay_copy(__t.end()) }
      |             ~~~~~~~~~~~~^~~~~~~~~~~
  136 |           { __decay_copy(__t.end()) }
      |           ~~^~~~~~~~~~~~~~~~~~~~~~~~~
  137 |             -> sentinel_for<decltype(_Begin{}(std::forward<_Tp>(__t)))>;
      |             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  282 |           { __t == __u } -> __boolean_testable;
      |             ~~~~^~~~~~
  514 |         typename iter_value_t<_In>;
      |         ~~~~~~~~~^~~~~~~~~~~~~~~~~~
  517 |         requires same_as<iter_reference_t<const _In>,
      |         ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  518 |                          iter_reference_t<_In>>;
      |                          ~~~~~~~~~~~~~~~~~~~~~~
T& operator*();
T& operator*() const;