_IsPtrType -- STL type checking on compile-time -- Substitution Failure Is Not An Error (SFINAE)

本文介绍了一种使用C++模板元编程进行类型检查的方法,包括如何将布尔值转换为类型(__true_type 和 __false_type),如何判断一个类型是否是指针类型,并通过编译时错误演示了检查的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

struct __true_type {};
struct
 __false_type {};
//bool to type

template <int _Is> struct __bool2type {
 typedef __true_type _Ret; 
};
template 
<> // icl supports both kinds of partial specialization

struct __bool2type<1> { typedef __true_type _Ret; };
// template <>

struct __bool2type<0> { typedef __false_type _Ret; };
//type to bool

template <class __bool_type>
struct __type2bool {
 
enum {_Ret = 1
};
};
template 
<class _Tp>  struct _IsPtr { enum { _Ret = 0
 }; };
// Partial specializations

template <class _Tp> struct _IsPtr<_Tp*> { enum { _Ret = 1 }; };
template 
<class _Tp>  struct
 _IsPtrType { 
 
enum { is_ptr = _IsPtr<_Tp>
::_Ret };
 typedef typename __bool2type
<is_ptr>
::_Ret _Type;
 
static _Type _Ret() { return
 _Type();} 
};  
//
 end of STL source
 
// Type checkers

void checkTrueType(const __true_type&) {}
void checkFalseType(const __false_type&
) {}
template
<class T>

void isPtrType(T) {
 checkTrueType(_IsPtrType
<T*>
::_Ret());
}  
 
template
<class T>

void notPtrType(T) {
 checkFalseType(_IsPtrType
<T*>
::_Ret());

int
 main()
{
 
char* it = 0
;
 isPtrType(it);
   notPtrType(it); 
// Compile-time error

 return 0;
}
//
 output: (Intel C++ Compiler 9.1)
//
 E:dhb's  DocumentsVC 6 Projects
//
 STL_CompileTime_TypeCheckCheckIterator.cpp(52): 
//
 error: no suitable user-defined conversion 
//
    from "_IsPtrType<char **>::_Type" 
//
    to "const __false_type" exists
//
    checkFalseType(_IsPtrType<T*>::_Ret());
//
   ^
//
           detected during instantiation of 
//
           "void notPtrType(T) [with T=char *]" 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值