如何定义 is_iterator 类型特征? [英] How to define is_iterator type trait?

查看:39
本文介绍了如何定义 is_iterator 类型特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 我正在尝试编写 is_iterator<T> 类型特征.当 T 是迭代器类型时 is_iterator::value == true 否则是 is_iterator::value == false.

  • I'm trying to code a is_iterator<T> type trait. Where when T is an iterator type is_iterator<T>::value == true otherwise is is_iterator<T>::value == false.

到目前为止我尝试了什么:

What I tried so far:

template <class, class Enable = void> 
struct is_iterator : std::false_type {};

template <typename T> 
struct is_iterator<T, typename std::enable_if<std::is_pointer<typename
     std::iterator_traits<T>::pointer>::value>::type> : std::true_type {};

现场演示

问:有没有比上面显示的更合适的方法来定义 is_iterator 类型特征?

Q: Is there a more proper way to define a is_iterator type trait than the one displayed above?

推荐答案

正如我在评论中所说,这里介绍的解决方案在某些实现中依赖于 iterators_traits 的不可移植属性.根据 C++03 和 C++11 标准,iterator_traits 仅为迭代器(以及指针的特殊情况)定义,因此任何其他用途都是未定义的行为.具体来说,在 SFINAE 上下文中使用 iterator_traits<T>::pointer 不能保证有效,因为实例化 iterator_traits<T> 将引用 T::value_typeT::pointerT::iterator_category 等,这发生在 SFINAE 不适用的直接上下文"之外.

As I said in comments, the solutions presented here rely on non-portable properties of iterators_traits in some implementations. According to the C++03 and C++11 standards, iterator_traits is only defined for iterators (and the special case of pointers) so any other use is undefined behaviour. Specifically, using iterator_traits<T>::pointer in a SFINAE context isn't guaranteed to work, because instantiating iterator_traits<T> will refer to T::value_type, T::pointer, T::iterator_category etc. and that happens outside the "immediate context" where SFINAE doesn't apply.

C++14 将解决这个问题 应该解决这个问题(它发生在 C++14 之后 DR 2408),但对于 C++11,定义 is_iterator 的安全方法是编写一个特征来检查迭代器必须定义的所有必需操作.所有迭代器都需要支持的唯一操作是 operator* 以及前后增量.不幸的是,有些类型定义了那些不是有效迭代器的操作,因此编写正确的 trait 非常困难.

C++14 will fix that was supposed to fix that (it happened post-C++14 with DR 2408), but for C++11 the safe way to define is_iterator is to write a trait that checks for all the required operations an iterator must define. The only operations that all iterators are required to support are operator* and pre- and post-increment. Unfortunately, there can be types that define those operations which are not valid iterators, so writing a correct trait is quite hard.

这篇关于如何定义 is_iterator 类型特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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