C++ 11标准STL中Traits的is_pointer的实现
2014-09-30 15:55
218 查看
在看STL的源码,发现is_pointer的模板调用,写了一个测试代码如下:
#include <iostream> #include <type_traits> using namespace::std; namespace iotek{ template<typename _Tp, _Tp __v> struct integral_constant { static constexpr _Tp value = __v; typedef _Tp value_type; typedef integral_constant<_Tp, __v> type; constexpr operator value_type() { return value; } }; template<typename _Tp, _Tp __v> constexpr _Tp integral_constant<_Tp, __v>::value; /// The type used as a compile-time boolean with true value. typedef integral_constant<bool, true> true_type; /// The type used as a compile-time boolean with false value. typedef integral_constant<bool, false> false_type; template<typename> struct __is_pointer_helper : public false_type { }; template<typename _Tp> struct __is_pointer_helper<_Tp*> : public true_type { }; template<typename> struct remove_cv; /// remove_const template<typename _Tp> struct remove_const { typedef _Tp type; }; template<typename _Tp> struct remove_const<_Tp const> { typedef _Tp type; }; /// remove_volatile template<typename _Tp> struct remove_volatile { typedef _Tp type; }; template<typename _Tp> struct remove_volatile<_Tp volatile> { typedef _Tp type; }; /// remove_cv template<typename _Tp> struct remove_cv { typedef typename remove_const<typename remove_volatile<_Tp>::type>::type type; }; /// is_pointer template<typename _Tp> struct is_pointer //: public integral_constant<bool, (__is_pointer_helper<typename remove_cv<_Tp>::type>::value)> : public integral_constant<bool, (__is_pointer_helper<_Tp>::value)> { }; /* public integral_const<bool,(_is_pointer_helper<remove_cv<int>::type>::value)> */ template <typename T> void foo(const T& val) { if(is_pointer<T>::value){ cout << "foo() called for a pointer " << endl; }else{ cout << "foo() called for a value" << endl; } } } using namespace::iotek; int main(int argc, char*argv[]) { int i = 0; foo(&i); return 0; }编译使用如下命令:
gcc -std=c++11 -o test is_pointer.cpp
相关文章推荐
- C++ 11 STL 线程库实现的线程同步与互斥
- 【C++ STL应用与实现】72: 标准库里的堆--如何使用标准库的heap算法
- C++ 11 STL 线程库实现的线程同步与互斥
- 【C++ STL应用与实现】19: 迭代器特性-iterator traits
- 标准C++中string类及STL容器类简介
- Thinking in c++ 2nd 习题解答之STL实现(一)
- 设计模式---单件(C++版) 比较通用的单件模式(STL实现)
- C++(STL)实现的修改游戏存档文件的2个相关类
- 标准纯C++实现简单的词法分析器(三)
- C++:STL标准入门汇总
- 自己实现了一下C++STL中的next_permutation,名为ant_next_permutation,发下代码
- 标准纯C++实现简单的词法分析器(二)
- C++:STL标准入门汇总
- C++ is on the way 11: 函数对象和Lambda表达式
- C++:STL标准入门汇总
- C/C++实现strcpy,strcat,strlen,strcmp标准实现代码
- C与C++中标准输入实现方式上的一点区别
- 标准纯C++实现简单的词法分析器(二)
- C++:STL标准入门汇总
- 词频统计的C++实现(使用stl--map)