Loki之类型识别

长平狐 发布于 2013/01/11 10:32
阅读 38
收藏 0

这是Loki里的类型识别的测试,分别测试普通类型,指针类型和类成员指针类型。


下面是测试代码,测试环境是gcc 4.6.3

NullType.h

#ifndef _NULLTYPE_INC_
#define _NULLTYPE_INC_

class NullType;

#endif


PointerTraits.h

#ifndef _POINTERTRAITS_INC
#define _POINTERTRAITS_INC 

#include "NullType.h"

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 PToMTraits
	{
		enum {result = false};
	};

	template <class U, class V> struct PToMTraits<U V::*>
	{
		enum {result = true};
	};

public:
	enum {isPointer = PointerTraits<T>::result};
	typedef typename PointerTraits<T>::PointeeType PointeeType;

	enum {isMemberPointer = PToMTraits<T>::result};
};


#endif

main.cpp

#include <iostream>
#include <vector>
using namespace std;

#include "PointerTraits.h"

class T
{
public:
	int a;
};

int main(int argc, char *argv[])
{
	bool iterIsPtr = TypeTraits<vector<int>::iterator>::isPointer;
	cout<<"vector<int>::iterator is "<<(iterIsPtr ? "pointer": "type")<<"\n";

	iterIsPtr = TypeTraits<int*>::isPointer;
	cout<<"int* is "<<(iterIsPtr ? "pointer": "type")<<"\n";

	iterIsPtr = TypeTraits<int*>::isMemberPointer;
	cout<<"int* is member pointer ("<<(iterIsPtr ? "yes": "no")<<")\n";

	/*
	 * int T::* 是一个指向类T的int的指针。
	 * 如:int T::* c = &T::a;
	 */

	//int T::* c = &T::a;
	iterIsPtr = TypeTraits<int T::*>::isMemberPointer;
	cout<<"int* is member pointer ("<<(iterIsPtr ? "yes": "no")<<")\n";

	return 0;
}

编译:g++ main.cpp

运行:./a.out

输出:

vector<int>::iterator is type
int* is pointer
int* is member pointer (no)
int T::* is member pointer (yes)





原文链接:http://blog.csdn.net/fjb2080/article/details/7904254
加载中
返回顶部
顶部