c++模板检测类型是否为class 原理

利用成员变量指针的实例化来实现

1
2
3
4
5
6
7
8
9
10
11
12
13
template<typename T>
struct
{
private:
template<typename U> static uint16 Func( int U::* );
template<typename U> static uint8 Func( ... );

public:
enum
{
Value = !__is_union( T ) && ( sizeof( Func<T>( 0 ) ) == sizeof( uint16 ) )
};
};

原理

int U::*为成员变量指针,指向U的int成员变量
若U为class或者struct,则该函数可被实例化
否则,该函数无法实例化