如何解决内部类不能使用 CRTP
我正在尝试将 CRTP 用于几种迭代器类型的通用功能。如此处所述 Using inner class with CRTP 内部类无法使用 CRTP,因此我将基本迭代器类移出容器类并在迭代器的容器内继承它。但我还是有
error: invalid use of incomplete type 'class ConcreteIteratorBase<Node<int>,std::iterator_traits<Node<int>*>,std::iterator<std::forward_iterator_tag,Node<int>,long int,Node<int>*,Node<int>&> >'
错误。
这是最小的可重现示例:
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <type_traits>
#include <utility>
template <typename T>
class NotEqFromEqMixin : public T
{
public:
bool operator!=(T const & other) const
{
return !(static_cast<T const &>(*this) == other);
}
};
template <typename Iterator,typename Traits,typename StdBase>
class IteratorHelperMixin : public NotEqFromEqMixin<Iterator>,public StdBase
{
public:
using pointer = typename Traits::pointer;
using reference = typename Traits::reference;
pointer operator->()
{
return &**this;
}
};
template <typename NodeT,typename TraitsT,typename StdBaseT>
class ConcreteIteratorBase
: public IteratorHelperMixin<ConcreteIteratorBase<NodeT,TraitsT,StdBaseT>,StdBaseT>
{
public:
using Super = IteratorHelperMixin<ConcreteIteratorBase<NodeT,StdBaseT>;
using typename Super::pointer;
using typename Super::reference;
ConcreteIteratorBase(pointer node) : node(node) {}
reference operator*() noexcept { return *node; }
bool operator==(ConcreteIteratorBase const & other) const noexcept { return node == other.node; }
protected:
pointer node;
};
template <typename Value>
class Node
{
public:
~Node() { delete next; }
Node* next = nullptr;
Value value;
};
template <typename Value>
class List
{
public:
using NodeType = Node<Value>;
void push(Value value)
{
NodeType* newNode = new NodeType();
newNode->value = value;
newNode->next = head;
head = newNode;
}
class iterator :
public ConcreteIteratorBase<
Node<Value>,std::iterator_traits<Node<Value>*>,Node<Value>>
>
{
using Super = ConcreteIteratorBase<
Node<Value>,Node<Value>>
>;
public:
iterator(NodeType* ptr = nullptr) : Super(ptr){}
iterator& operator++()
{
if (this->node)
{
this->node = this->node->next;
}
return *this;
}
Value& operator*()
{
return this->node->value;
}
bool operator==(const iterator& other) const
{
return this->node == other.node;
}
};
iterator begin()
{
return iterator{head};
}
iterator end()
{
return iterator{};
}
NodeType* head = nullptr;
};
int main(int,char**)
{
List<int> list;
for (int i = 0; i < 10; ++i)
{
list.push(i);
}
for(auto & val : list)
{
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
解决方法
您的问题是您在进行循环继承时滥用了 CRTP:
ConcreteIteratorBase
-> IteratorHelperMixin<ConcreteIteratorBase,..>
-> NotEqFromEqMixin<ConcreteIteratorBase>
-> ConcreteIteratorBase
你应该在这里放弃继承
template <typename T>
class NotEqFromEqMixin //: public T
// ^^^^^^^^^^^^
{
public:
bool operator!=(T const & other) const
{
return !(static_cast<T const &>(*this) == other);
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。