• C++ type_traits 原理


    一、简单介绍

    (1)、type_traits 类型萃取,C++11中已经成为了一个核心模块。

    (2)、标准库包括helper classestype traitstype transformations 三个模块。

                                                                                                                                                                                                                         

    (3)、type_traits是编译期就去确定具体的类型,从而根据不同的类型来执行不同的模块,消除重复,提高代码质量。

    二、实现

       C++标准库中的type_traits使用方式这里不再介绍,我也在学习中,我这里根据自己的理解,来记录下type_traits的实现方式。

    核心:模板

    (1)、理解模板template的用法。

    (2)、理解模板template特化(全特化和偏特化)。

     

    简单实现C++标准库的is_unsigned

     1 template <typename T>
     2 struct isUnsigned
     3 {
     4     static const bool value = false;
     5 };

    首先是一个支持所有类型模板isUnsigned, isUnsigned(unsigned)::value 毫无疑问是flase;

    那如何使isUnsigned(unsigned)::valuetrue呢,那就需要增加一个unsigned的特化版本的isUnsigned

    template <>
    struct isUnsigned<unsigned>
    {
        static const bool value = true;
    };

    此时,编译器在编译期间执行isUnsigned(unsigned)::value则会定位到此特化版本的模板类型。

    测试代码

    1 int main()
    2 {
    3     cout << isUnsigned<int>::value << endl;
    4     cout << isUnsigned<float>::value << endl;
    5     cout << isUnsigned<bool>::value << endl;
    6     cout << isUnsigned<unsigned>::value << endl;
    7 
    8     return 0;
    9 }

    测试结果     

       

  • 相关阅读:
    10.13 新版本go on~
    9.30 总结一下九月呗
    9.25 学习下日期加减
    9.22 迎难而上不要怂!
    9.22 Sans-serif VS Serif
    9.22 keep studying
    【LeetCode刷题】最长同值路径:妙解
    【LeetCode刷题】机器人走路最大距离:妙解
    【LeetCode刷题】不使用+-的加减法:妙解
    【LeetCode刷题】NIM游戏:妙解
  • 原文地址:https://www.cnblogs.com/Forever-Kenlen-Ja/p/7074228.html
Copyright © 2020-2023  润新知