C++ 11標準STL中Traits的is_pointer的實現

在看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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章