template<typename T,typename U>
struct same_type
{
static const bool value = false;
};
template<typename T>
struct same_type<T,T>
{
static const bool value = true;
};
char test_func()
{
return ''; //error, return empty char constant
return ' '; //ok
}
/ *特化*/
// dummy type, don't define
struct smart_any_cannot_dereference;
// For use in implementing unary operator*
template<typename T>
struct deref
{
typedef smart_any_cannot_dereference type; // will cause a compile error by default
};
在特化前必须有模板的完全定义
template<typename T>
struct deref<T*>
{
typedef T& type; // The result of dereferencing a T*
const static int value = 123;
};
/一个特殊的类型/
template<typename T>
struct has_unused
{
private:
template<class U,int U::*> struct wrap_t;
template<typename U> static yes_t check( wrap_t<U,&U::unused>* );
template<typename U> static no_t __cdecl check( ... );
public:
static bool const value = ( sizeof(check<T>(0)) == sizeof(yes_t) );
};
//要使value返回true,U必须有一个成员变量unused
struct HANDLE_
{
int unused;
};
同时,sizeof(check<T>(0))虽会返回对应的check函数return type,但函数不会被调用,我查看过汇编代码,直接显示的返回类型的大小,没有函数调用
/类型安全/
template<bool>
struct static_assert;
template<>
struct static_assert<true>
{
static_assert() {}
};
//使用方法如下:
static_assert<0 != sizeof(T)> no_complete_type
由于没有定义struct static_assert<false>{};类型,编译会出错