zoukankan      html  css  js  c++  java
  • STL之traits编程技法

        traits编程技法利用了“内嵌型别”的编程技巧与编译器的template参数推导功能。

    下面主要看看利用traits编程技法实现的迭代器萃取机制。

    5种迭代器类型定义:

    struct input_iterator_tag {};
    struct output_iterator_tag {};
    struct forward_iterator_tag : public input_iterator_tag {};
    struct bidirectional_iterarot_tag : public forward_iterator_tag {};
    struct random_access_iterator_tag : public bidirectional_iterarot_tag {};

    std::iterator的定义

    template <class Category, class T, class Distance = ptrdiff_t, 
              class Pointer = T*, class Reference = T&>
    struct iterator {
        typedef Category    iterator_category;
        typedef T           value_type;
        typedef Distance    difference_type;
        typedef Pointer     pointer;
        typedef Reference   reference;
    };

        如果想和STL协同工作,自行定义的迭代器必须定义iterator_categoryvalue_typedifference_typepointerreference这五大内嵌型别。为了方便,STL定义了std::iterator这个基类,自定义的迭代器只要继承这个基类

    就可以了。但要注意的是,并不是STL中的所有迭代器都继承了这个基类,比如_deque_iterator。

    "榨汁机"traits

    template <class Iterator>
    struct iterator_traits {
        typedef typename Iterator::iterator_category  iterator_category;
        typedef typename Itetator::value_type         value_type;
        typedef typename Iterator::difference_type    difference_type;
        typedef typename Iterator::pointer            pointer;
        typedef typename Iterator::reference          reference;
    };

        由于原生指针也是一种迭代器,但是原生指针没有内嵌型别,因此,iterator_traits需要为原生指针提供特化版本。

    template <class T>
    struct iterator_traits<T*> {
        typedef random_access_iterator_tag  iterator_category;
        typedef T         value_type;
        typedef ptrdiff_t    difference_type;
        typedef T*            pointer;
        typedef T&          reference;
    };
    
    template <class T>
    struct iterator_traits<const T*> {
        typedef random_access_iterator_tag  iterator_category;
        typedef T         value_type;
        typedef ptrdiff_t    difference_type;
        typedef const T*            pointer;
        typedef const T&          reference;
    };

      

  • 相关阅读:
    linux面试常问命令
    图卷积网络 GCN Graph Convolutional Network(谱域GCN)的理解和详细推导
    总结一些牛客网上 的算法岗面试题
    Pytorch-Tensor基本操作
    C++使用代码创建一个Windows桌面应用程序
    Windows中的消息与消息队列
    解决COM组件在WPF设计器中命名空间不存在XXX的问题(附带如何在WPF中使用APlayer引擎)
    Mybatis的一级缓存
    面试题:zookeeper实现分布式锁
    sublime text 文件默认打开格式
  • 原文地址:https://www.cnblogs.com/gattaca/p/4701181.html
Copyright © 2011-2022 走看看