C++ 模板中的类型获取

1. 类型判断

  • 严格类型比较:std::is_same<T1, T2>::value

    cout << std::is_same<int, int>::value << endl; // true
    cout << std::is_same<int, long>::value << endl; // false
    cout << std::is_same<int, unsigned int>::value << endl; // false
    cout << std::is_same<int, const int>::value << endl; // false
    cout << std::is_same<int, int&>::value << endl; // false
    cout << std::is_same<int, int*>::value << endl; // false
  • 退化类型比较:std::decay<T>::type

    cout << std::is_same<int, std::decay<int>::type>::value << endl; // ture
    cout << std::is_same<int, std::decay<long>::type>::value << endl; // false
    cout << std::is_same<int, std::decay<unsigned int>::type>::value << endl; // false
    cout << std::is_same<int, std::decay<const int>::type>::value << endl; // true
    cout << std::is_same<int, std::decay<int&>::type>::value << endl; // ture
    cout << std::is_same<int, std::decay<int*>::type>::value << endl; // false

2. 容器元素类型

  • STL 的容器支持: Container::value_type

    using type = Container::value_type;

3. 迭代器类型

  • 头文件:#include <type_traits>
  • using type = std::iterator_traits<Itr>::value

4. 函数返回类型

  • std::result_of<Func()>::type

5. 举两栗子

  • 判断STL容器是否包含某元素:

    • 当容器元素为基本类型时:
    // map::value_type is const std::pair<const T, T>
    // need reload operator "==" to pass compile
    template <class T>
    bool operator==(const pair<const T,T> p1, const pair<T,T> p2){return p1.first==p2.first && p1.second==p2.second;
    }// basic value type
    template <class Container, class ItemType>
    int isContain(Container const &container, ItemType const &item){using type = typename std::decay<typename Container::value_type>::type;bool isSame = std::is_same<type, typename std::decay<ItemType>::type>::value;if(!isSame){cout << "error type not same " << endl;return -1;} else {int index=0;for(auto itr = container.begin();itr != container.end();){if(*itr == item){break;} else {itr++;index++;}}return index;}
    };
    • 当元素类型为自定义的class或struct时:
    // user defined value type
    template <class Container, class ItemType>
    int isContain(Container const &container, ItemType const &item, bool func(ItemType const, ItemType const)){using type = typename std::decay<typename Container::value_type>::type;bool isSame = std::is_same<type, typename std::decay<ItemType>::type>::value;if(!isSame){cout << "error type not same " << endl;return -1;} else {int index=0;for(auto itr = container.begin();itr != container.end();){if(func(*itr, item)){break;} else {itr++;index++;}}return index;}
    };
  • 对STL容器的元素求和:

    元素为基本类型时,用std::accumulate(container.begin(), container.end(), 0);即可,

    当元素为自定义的类型时:

    template <typename Container, typename ItemType>
    ItemType accumulate(Container container, ItemType getValue){ItemType sum;for (int i = 0; i < container.size(); ++i) {sum += getValue(container.at(i));}return sum;
    }
    struct Pt{
    int x;
    int y;
    }int getValue(Pt pt){ return pt.x;}int main(){
    vector<Pt> pts = {{1,2}, {2,3}, {3,4}};
    auto sum = accumulate(pts,getValue); // 运行OK
    return 0;
    }
    

    这样写模板函数,type ItemType 当作函数的返回类型, 传入匿名(lambda) 函数时会报错不能通过编译
    mismatched types ... main()::<lambda(int)>
    例如:

    auto getValueX = [](Pt pt)->int{return pt.x;};
    auto sum = accumulate(pts,getValueX);

    或者:

    auto sum = accumulate(pts,[](Pt pt){return pt.x;});

    所以模板函数传入的函数应该是函数指针类型, 返回类型用std::result_of获取:

    template<typename Container, typename Func>
    auto add(Container& container, Func getValue) -> typename std::result_of<Func(typename Container::value_type)>::type {using type = typename std::result_of<Func(typename Container::value_type)>::type;type sum  = getValue(container.at(0));for (int i = 0; i < container.size(); ++i) {sum += getValue(container.at(i));}return sum;
    }

C++ 模板中的类型获取(一)相关推荐

  1. 再Repeater模板中,如何获取里面的控件 客户端ID ??

    问题: <asp:Repeater ID="rptList" runat="server">   <ItemTemplate>   &l ...

  2. EJS 模板中,js 如何获取后端传来的数据

    在 ejs 模板中,想让 js 的代码获得后端传来的数据,要在<%=%>的外面加一对引号. 如下图,从后端给 chatroom.ejs 传进去一个 avatar 变量,是个字符串类型的. ...

  3. python中使用sys模板和logging模块获取行号和函数名的方法

    From: http://www.jb51.net/article/49026.htm 这篇文章主要介绍了python中使用sys模板和logging模块获取行号和函数名的方法,需要的朋友可以参考下 ...

  4. Django模板中如何将函数的变量作为字典key并获取对应的value

    Django模板中如何将函数的变量作为字典key并获取对应的value 问题 现有一字典 mydict = {'abc': 123} key = 'abc' 传入到模板后 在模板html中你可能像下面 ...

  5. mysql java 获取周_Java中获取Mysql中datetime类型的数据

    由于Java中的日期类型只有Date类型,而Mysql中即有date型,又有datetime型,当我们想要在java中获取Mysql中datetime类型的数据或向Mysql数据库中插入datetim ...

  6. 解决laytpl.js模板引擎插件加载模板后无法获取模板中的元素id等内容

    一.问题描述 在页面中使用laytpl.js模板引擎,在页面加载后无法使用jquery获取模板中的html元素,以下是图片和代码: 在添加或修改完毕后重新加载页面,不能使用jquery获取模板中的ht ...

  7. arcpy中拆分获取FeatureClass中各类型地物要素到单独的shp中,类似于splitShp的功能(地理国情监测)

    arcpy中拆分获取FeatureClass中各类型地物要素到单独的shp中,类似于splitShp的功能:(地理国情监测) for str_Val in set(shp_JH_list): #循环该 ...

  8. python获取List数组中重复元素的个数(arcpy中统计FeatureClass中各类型地物要素的图斑数)(地理国情监测)

    python获取List数组中重复元素的个数(arcpy中统计FeatureClass中各类型地物要素的图斑数)(地理国情监测) for str_Val in set(shp_JH_list): #循 ...

  9. 如何在组件模板中选择元素?

    本文翻译自:How can I select an element in a component template? Does anybody know how to get hold of an e ...

最新文章

  1. ssm 实现房屋租赁系统
  2. 创建mysql数据库,在新数据库中创建表,再尝试删除表
  3. html模板存储在mysql_Python爬虫架构5模板 | 你真的会写爬虫吗?
  4. Netty - I/O模型之BIO
  5. c++新特性11 (10)shared_ptr七reset
  6. linux运行rmp文件,linux 里rpm包到底是干什么用的啊?
  7. SAP Spartacus cx-page-layout 属性运行时的赋值原理, set 是如何被框架调用的?
  8. NOIP模拟测试7「方程的解·visit」
  9. mysql 事b务 查询_MySQL进阶学习笔记二(包括连接查询、子查询、联合查询、事务、存储过程)...
  10. 4-8 :button表单按钮选择器
  11. Bailian1183 POJ1183 反正切函数的应用【迭代计算】
  12. python collections.Counter
  13. Android mes系统源码,基于Android的MES监控系统设计与开发
  14. 【错误信息】Maximum call stack size exceeded
  15. Wireshark捕获IP报文——分片与不分片
  16. kindle索引_Kindle 卡索引问题解决方法汇总
  17. 什么是验收测试?一份详细向导
  18. 重庆计算机二级成绩查询2020年12月,重庆2020年12月计算机等级考试成绩查询入口已开通...
  19. 华为荣耀畅玩7安卓系统升级为鸿蒙系统,华为EMUI系统迎来绝唱!内核升级为鸿蒙,荣耀被彻底放弃?...
  20. html评价标准展示,网页设计评分标准.doc

热门文章

  1. 软考高级 真题 2010年上半年 信息系统项目管理师 综合知识
  2. 微信公众号都有哪些传播方式吸引粉丝
  3. Odoo 仓库出入库 使用电子秤(地磅)称重获取数量。
  4. Anemometer安装
  5. python 正则 匹配任意字符串_python中正则匹配
  6. IMDG产品功能扩展
  7. 2022年3月15日黑马第三天
  8. 石头剪子布(字符串)c语言,石头、剪刀、布程序,C语言模拟
  9. Web APIs day6 | 正则阶段案例
  10. Python +appium 报错:NoSuchElementException: Message: An element could not be located on the page using