为什么不推荐使用std :: iterator? [英] Why is std::iterator deprecated?

查看:507
本文介绍了为什么不推荐使用std :: iterator?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模板类 std :: iterator 设置为在C ++ 17中不推荐使用。为什么这样?确保 std :: iterator_traits code> 可以工作,尤其是在您可以使用默认模板参数的情况下。在C ++ 17中还有其他方法吗?

Template class std::iterator is set to be deprecated in C++17. Why so? It has been a handy way to make sure std::iterator_traits works, especially if you can make use of the default template arguments. Is there some other way of doing it in C++17?

推荐答案

来自建议弃用该提案


作为编写迭代器类的辅助工具,原始标准库提供了迭代器类模板,以自动声明iterator_traits对每个迭代器期望的五个typedef的声明。然后在库本身中使用它,例如在 std :: ostream_iterator

template <class T, class charT = char, class traits = char_traits<charT> >
class ostream_iterator:
  public iterator<output_iterator_tag, void, void, void, void>;

void 参数的长序列很多对读者而言,这还不如在类定义本身中简单地提供预期的typedef,这是当前工作草案所采用的方法,遵循C ++ 14中设置的模式,在该模式中,我们从 unary_function binary_function

The long sequence of void arguments is much less clear to the reader than simply providing the expected typedefs in the class definition itself, which is the approach taken by the current working draft, following the pattern set in C++14 where we deprecated the derivation throughout the library of functors from unary_function and binary_function.

迭代器模板还为那些不方便的人提供了一个陷阱,因为在典型用法中,它将是一个依赖的基类,这意味着在名称查找过程中,它将不会从该类或其成员函数中进行查找。这导致惊讶的用户试图理解为什么以下简单用法不起作用:

In addition to the reduced clarity, the iterator template also lays a trap for the unwary, as in typical usage it will be a dependent base class, which means it will not be looking into during name lookup from within the class or its member functions. This leads to surprised users trying to understand why the following simple usage does not work:

#include <iterator>

template <typename T>
struct MyIterator : std::iterator<std::random_access_iterator_tag, T> {
   value_type data;  // Error: value_type is not found by name lookup 

   // ... implementations details elided ...
};

仅出于澄清的原因就足以说服LWG将标准库规范更新为不再需要标准迭代器适应程序是从 std :: iterator 派生的,因此在标准本身中不再使用此模板。因此,它似乎是不推荐使用的强大候选对象。

The reason of clarity alone was sufficient to persuade the LWG to update the standard library specification to no longer mandate the standard iterator adapators as deriving from std::iterator, so there is no further use of this template within the standard itself. Therefore, it looks like a strong candidate for deprecation.

您还可以在 LWG 2438 。 (h / t TC

You can also see STL's reasoning in LWG 2438. (h/t T.C.)

至于其他方法,并非如此。您基本上可以实现自己的 std :: iterator 版本(不太难),也可以手动写出所有这些typedef(也不难),为了清楚起见,我实际上更喜欢它)。

As for some other way of doing it, not really. You could basically implement your own version of std::iterator (which isn't too hard) or manually write out all of those typedefs (which isn't too hard either, and I actually prefer it for clarity).

这篇关于为什么不推荐使用std :: iterator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆