boost学习之-enable_if
来源:互联网 发布:atm模拟系统源码 编辑:程序博客网 时间:2024/05/16 19:18
用法:
1
你需要在把一个符合某些条件的函数加入到或排除出重载决议集合中。
你需要根据某个条件将一个类模板的特化版本加入到或排除出特化集合中。
void some_func(int i)
{
std::cout << "void some_func(" << i << ")\n";
}
template <typename T> void some_func(
T t,typename boost::disable_if<
boost::is_integral<T> >::type* p=0)
{
typename T::type variable_of_nested_type;
std::cout << "template <typename T> void some_func(T t)\n";
}
int mian
{
short s=12;
some_func(s);
return 0
}
如果第二个函数没有,typename boost::disable_if<boost::is_integral<T> >::type* p=0参数,编译该程序会报错,错误原因是main中采用了
模版形式的some_func函数,为了排除该模板函数,而采用第一个int参数的some_func,需要用到disable_if;
disable_if在boost实现中相关代码如下:
template <bool B, class T = void>
struct disable_if_c {
typedef T type;
};
template <class T>
struct disable_if_c<true, T> {};
template <class Cond, class T = void>
struct disable_if : public disable_if_c<Cond::value, T> {};
如果T是int类型或short类型,编译器会推演实现如下形式的类,也是disable_if的基类,
template <class T>
struct disable_if_c<true, T> {};
该类没有定义typedef type,所以不会实例化模板形式的some_func,所以
模板形式的some_func也不会成为模板推演中的候选函数,所以就被排除在外了;
这个就是:disable_if的内部原理,通过阻止函数的实例化,达到成为模板推演候选函数的目的;
综上,disable_if的原理有点难以理解,但是还是有很大作用的,在实际中,我感觉只要不是要实现boost库之类的库,一般都不会用到这个东西;
- boost学习之-enable_if
- C++学习 boost学习之-enable_if
- Boost::Utility库 之enable_if
- boost::enable_if 详解
- boost.core.enable_if
- boost::enable_if与SFINAE原则
- c++11之enable_if
- enable_if
- enable_if
- enable_if
- enable_if
- Boost学习之Boost简介
- 【boost学习】之boost::bind
- boost学习之Boost.Lambda
- boost enable_if——SFINAE(匹配失败不是错误)
- 学习boost之lexical_cast
- 学习boost之format
- 学习boost之filesystem
- 广播通信
- Android NDK环境搭建
- APNS 证书生成注意事项
- Groovy 操作xml
- 0706
- boost学习之-enable_if
- windows网文
- Groovy 操作json
- C++类型转换操作符之间的区别
- 一键搞定Java桌面应用安装部署 —— exe4j + Inno Setup 带着JRE, 8M起飞
- 多去阅读思维训练类的书籍
- 比起“呵呵”,我宁愿听到一句:我现在不想聊天,滚蛋。
- Spring中Bean的4种依赖检查模式
- 很好的C#视频教程