所谓Type trait,提供了一种用来处理type 属性的办法,它是个template,可在编译期根据一个或多个template实参(通常也是type)产出一个type或者value。

template <typename T>
void foo(const T& val) {
if (std::is_pointer<T>::value) {
cout << "foo called for a pointer " << endl;
}
else
cout << "foo() called for a value" << endl;
//...
}

trait std::is_pointer定义于<type_traits>,用来检查T是否pointer type。若是,就是 type true_type,否则type false_type。而::value若非产生true就是false。

但是,不能如下这么做:

template <typename T>
void foo(const T& val) {
std::cout << (std::is_pointer<T>::value ? *val : val) << endl;
}

关键是不确定val到底是指针还是普通值。若是个值得话,*val 就无效了,不能通过编译。

template <typename T>
void fool_impl(const T& val,std::true_type){
cout << "foo() called for pointer to " << *val << endl;
} template<typename T>
void fool_impl(const T7 val, std::false_type){
cout << "foo() called value to "<< val << endl;
} template<typename T>
void foo(const T& val){
fool_impl(val,std::is_pointer<T>());
}

这比重载版本要好。是因为,有时候太多重载版本并无必要。一般而言,type trait 的威力来自于一个事实:它们是泛型代码的基石。

两个例子:

1 针对整数的弹性重载

假设一个函数foo(),对于整数类型和浮点类型的实参有不同的实现。通常做法是重载:

void foo(short);
void foo(unsigned short);
void foo(int);
...
void foo(float);
void foo(double);
void foo(long double);

每多一个类型,就需要一个新的重载函数。但是,有了type trait就是不一样:

template <typename T>
void foo_impl(T val, true_type); template<typename T>
void foo_impl(T val, false_type); template<typename T>
void foo(const T& val){
fool_impl(val,std::is_integral<T>());
}

只需提供两份实现,整数和浮点,完事儿。

2 处理共通类型

共通类型是一个可以“用来处理两个不同类型的值”的类型,前提是存在这个一个共通类型。举例而言,不同类型的两个值的总和或最小值,就该使用共通类型。

template<typename T1, typename T2>
typename std::common_type<T1,T2>::type min(const T1& x, const T2& T);

如果两个实参都是int 或者都是long,或者一个是int一个是long,std::common_type<T1,T2>::type 会产生int。如果实参之一是string而另一个是字符串字面常量,就产生std::string.  其通过以下规则实现:

template<typename T1, typename T2>
struct common_type<T1,T2>{
typedef decltype(true ? decval<T1>() : decval<T2>()) type;
};

其中 decltype是c++11提供的关键字,用以到处表达式类型,declval()是辅助性trait,依据传入的类型提供一个值 ,但是不去核算它。

该头文件下的函数等 。cppreference.com

Type Trait 和 Type Utility的更多相关文章

  1. input[type='submit']input[type='button']button等按钮在低版本的IE下面,去掉黑色边框的问题

    今天做一个tabs效果的时候,发现上面的button在低版本下会出现黑色的边框,很难看,于是我整理了下几个去掉黑色边框的办法: 1.在button的外层嵌套一个div,设置button的border: ...

  2. #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

    #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)宏的运行机理:1. ( (TYPE *)0 ) 将零转型为TY ...

  3. type和create type

    type和create type 异同点:      create type 可在库中生成一个长期有效的自定义类型对象,而type作用域仅限于语句块中:      两者都可以自定义数据类型: 各种ty ...

  4. There is no result type defined for type 'json' mapped with name 'success'. Did you mean 'json'?

    错误信息: 严重: Exception starting filter struts2 Unable to load configuration. - action - file:/C:/Users/ ...

  5. form表单重复提交,type=“button”和type=“submit”区别

    公司测试提了一个项目后台在IE浏览器下(360,firefox就没问题)出现数据重复的问题,调试了好久终于发现问题所在,也不知道是谁写的代码,醉醉的.... 错误地点: <input type= ...

  6. swift 中Value Type VS Class Type

    ios 中Value Type 和 Class Type 有哪些异同点,这个问题是在微信的公共帐号中看到的,觉得挺有意思,这里梳理一下. 1.swift 中为什么要设置值类型? 值类型在参数传递.赋值 ...

  7. Failed to register Grid Infrastructure type ora.mdns.type

    安装11g的集群软件的时候,在最后运行root.sh脚本时候,没有执行成功,最后提示如下错误: [root@r2 ~]# /u01/app/11.2.0/grid_1/root.sh Performi ...

  8. Springs Element 'beans' cannot have character [children], because the type's content type is element-only

    Springs Element 'beans' cannot have character [children], because the type's content type is element ...

  9. Type I and type II errors | 第一类错误和第二类错误

    偶尔能看懂,但是死活记不住,归根结底是没有彻底理解! Type I and type II errors - wiki type I error is the rejection of a true  ...

随机推荐

  1. 五十五:WTForms表单验证之渲染模板

    此功能看似强大,实则鸡肋 from wtforms import Form, StringField, BooleanField, SelectFieldfrom wtforms.validators ...

  2. IDEA 常用插件及快捷键总结

    现在开发中和日常自己开发都统一换成了 IDEA 进行开发了.现在针对自己常用到的插件和快捷键进行总结记录下. 插件 Alibaba Java Coding Guidelines:阿里巴巴编码规约 Gr ...

  3. MongoDB数据节点基础操作

    1.查看集群中各节点的状态: rs0:PRIMARY> rs.status() 2.查看集群中各节点配置情况: rs0:PRIMARY> rs.conf() 3.主节点降级为从节点: rs ...

  4. java:工具(汉语转拼音,压缩包,EXCEL,JFrame窗口和文件选择器,SFTP上传下载,FTP工具类,SSH)

    1.汉语转拼音: import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuP ...

  5. python-Web-数据库-Redis

    概述: >>>安装: >>>数据类型: string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合) &g ...

  6. 【Linux开发】linux设备驱动归纳总结(五):4.写个简单的LED驱动

    linux设备驱动归纳总结(五):4.写个简单的LED驱动 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ...

  7. hadoop的目录结构介绍

    hadoop的目录结构介绍 解压缩hadoop 利用tar –zxvf把hadoop的jar包放到指定的目录下. tar -zxvf /home/software/aa.tar.gz -C /home ...

  8. DDOS常见攻击类型和防御措施

    DDOS 攻击类型: SYN Flood 攻击 ACK Flood 攻击 UDP Flood 攻击 ICMP Flood 攻击 Connection Flood 攻击 HTTP Get 攻击 UDP ...

  9. 大型软件公司.Net面试常见题(含答案)

    1.a=10,b=15,在不用第三方变量的前提下,吧a.b互换 2.已知数组int[] max={6,5,2,9,7,4,0};用快速排序算法按降序对其进行排列,并返回数组 3.请简述面向对象的多态的 ...

  10. AssertionError [ERR_ASSERTION]: Task function must be specified,gulp版本不一致

    报错信息: vue项目打包报错 > innovate-admin-vue@ build /home/soldier/SOLDIER/IDE_project/webStorm_project/in ...