文章目录
目的
类型特征的主要作用就是在编译时根据类型来做决定. 这使得代码更加清晰, 可维护.
实现
class NullType {};
template<typename T>
class TypeTraits
{
private:
template<class U> struct PointerTraits
{
enum { result = false };
typedef NullType PointeeType;
};
template<class U> struct PointerTraits<U*>
{
enum { result = true };
typedef U PointeeType;
};
template<class U> struct ReferenceTraits
{
enum { result = false };
typedef NullType ReferencedType;
};
template<class U> struct ReferenceTraits<U&>
{
enum { result = true };
typedef U ReferencedType;
};
public:
enum { isPointer = PointerTraits<T>::result
, isReference = ReferenceTraits<T>::result };
typedef typename PointerTraits<T>::PointeeType PointeeType;
typedef typename ReferenceTraits<T>::ReferencedType ReferencedType;
};
测试
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
const bool isPointer = TypeTraits<vector<int>::iterator>::isPointer;
cout << (isPointer ? "pointer" : "not pointer") << endl;
const bool isRef = TypeTraits<int&>::isReference;
cout << (isRef ? "ref" : "not refer") << endl;
return 0;
}
输出
not pointer
ref