码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 11标准STL中Traits的is_pointer的实现

时间:2014-09-30 17:38:29      阅读:523      评论:0      收藏:0      [点我收藏+]

标签:c++11   stl   

在看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中Traits的is_pointer的实现

标签:c++11   stl   

原文地址:http://blog.csdn.net/bizzareblizzard/article/details/39696929

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!