Loki之类型识别

这是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)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值