如何解决确定模板中模板参数的类型
我正在尝试在C ++中实现通用的链表和链表迭代器。我有一个如下的节点结构
template <typename T>
struct Node
{
T m_data;
Node<T>* m_next;
};
我还有一个链表迭代器,它是一个模板,因此它可以生成常规迭代器和const
迭代器。
template <typename NodeType>
class LinkedListIterator
{
private:
NodeType* m_node;
public:
LinkedListIterator(NodeType* n);
T& operator*() const;
};
我的问题是如何正确声明operator*()
函数?我的期望是像下面这样的东西
LinkedListIterator<const Node<T>> my_iter(some_node_pointer);
*my_iter = new_value; // should not work
我了解到,在T
中返回operator*()
没有意义,因为此类无法访问Node
类中的类型名称。
我找到了解决方法,就像在Node
类中为类型创建别名一样
template <typename T>
struct Node
{
typedef T type_value;
// rest of Node class...
};
现在我可以在迭代器类中进行以下操作
template <typename NodeType>
class LinkedListIterator
{
public:
typename NodeType::type_value& operator*() const;
};
这似乎起作用,并且将返回正确的值。所以我的问题确实应该是,这是实现此目标的最佳方法吗?我是否需要typedef
创建别名才能使用该类型?还是有一种方法可以确定LinkedListIterator
类中的类型?
解决方法
像这样使用typedef
是做到这一点的规范方法,并且经常在标准库中完成。实际上,所有LegacyIterators都应定义value_type
,difference_type
,reference
,pointer
和iterator_category
。只有这样,才能使用std::iterator_traits
普遍访问它们的特征。
例如:
// a simple forward iterator
struct Iterator {
using value_type = int;
using reference = value_type &;
using pointer = value_type *;
using difference_type = std::ptrdiff_t;
using iterator_category = std::forward_iterator_tag;
// LegacyIterators also need two operators to be defined:
// the result of operator* is unspecified,we can choose it freely
value_type operator*();
// operator++ needs to return a reference to self
Iterator& operator++();
};
// we can now access the traits universally,as can various standard library functions
static_assert (std::is_same_v<std::iterator_traits<Iterator>::value_type,int> );
总而言之,您正在做的事情是正确的解决方法,但是您应该坚持使用这些确切的名称,以便标准库可以访问迭代器的特征。我也建议使用using
而不是typedef
。它不仅具有=
作为视觉分隔符,而且普遍适用,例如它可以像typedef
一样被模板化。参见What is the difference between 'typedef' and 'using' in C++11?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。