本文专门记录学习过程中碰到的关于模板的一些技巧:
1. 使用IsOfClassType类判断一个数据类型是否是class。
template<typename T> class IsOfClassType {
public:
template<typename U> static char check(int U::*);
template<typename U> static float check(...);
public:
enum { Result = sizeof(check<T>(0)) };
};
2.
template <typename _T>
class A{};
class B: public A< B >{
};
3.强制类型转换
template<typename dst_type,typename src_type>
dst_type union_cast(src_type src) {
union {
src_type src;
dst_type dst;
} u = {src};
return u.dst;
}
4.编译期计算数组元素个数
template <typename _CountofType, size_t _SizeOfArray>
char (*__countof_helper( _CountofType (&_Array)[_SizeOfArray]))[_SizeOfArray];
#define _countof(_Array) sizeof(*__countof_helper(_Array))
5.判断类里面是否包含某个函数(有点类似__if_exists)
template<class CLS> struct if_bar_exists { private: struct Exists { char x; }; struct NotExists { char x[2]; }; template< void (CLS::*)( void ) > struct Param; template<class T> static Exists detect( Param<&T::bar>* ); template<class T> static NotExists detect( ... ); public: static const bool val = ( sizeof(detect<CLS>(0)) == sizeof(Exists) ); }; struct foo1 { void bar( void ); }; struct foo2 { void bar( int ); }; int main() { std::cout << if_bar_exists<foo1>::val << std::endl; std::cout << if_bar_exists<foo2>::val << std::endl; return 0; }
评论