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