程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> c++ 泛型 之 TypeTraints

c++ 泛型 之 TypeTraints

編輯:C++入門知識

c++ 泛型 之 TypeTraints


 

#ifndef TYPETRAITS_H_
#define TYPETRAITS_H_

//只有聲明,沒有定義,它只能被用來表示“我不是個令人感興趣的型別”。
class NullType;
//這是一個可被繼承的合法型別,而且你可以傳遞EmptyType對象。
class EmptyType{};

//1. 常整數 映射為型別
/*
根據不同的數值產生不同的型別。一般而言,符合下列條件便可使用Int2Type
1. 有必要根據某個編譯期常數調用一個或數個不同的函數
2. 有必要在編譯期實施“分派”(dispatch)(if else 型分派要求每個條件都要編譯通過,而通過
   Int2Type不會產生類似問題,因為編譯期不會去編譯一個未被使用到的template函數(如果一個template的
   成員函數未曾被真正使用上,c++不會將它具現化)。
*/
template
struct Int2Type
{
	enum{value = v};
};

//Type2Type 唯一作用就是消除重載函數的歧義(模稜兩可)。
////////////////////////////////////////////////////////////////////////////////
// class template Type2Type
// Converts each type into a unique, insipid type
// Invocation Type2Type where T is a type
// Defines the type OriginalType which maps back to T
////////////////////////////////////////////////////////////////////////////////

template 
struct Type2Type
{
	typedef T OriginalType;
};
//型別選擇,根據第一個引數判斷是用第二個參數還是第三個參數
template
struct Select
{
	typedef T Result;
};
template
struct Select
{
	typedef U Result;
};

//Type Traits

template 
class TypeTraints
{
private:
	templatestruct PointerTraints
	{
		enum{result = false};
		typedef NullType PointerType;
	};
	templatestruct PointerTraints
	{
		enum{result = true;};
		typedef U PointerType;
	};
	templatestruct PtoMTraits
	{
		enum{result = false};
	};
	template
	struct PtoMTraits
	{
		enum{result = true};
	};
public:
	enum
	{
		isPointer = PointerTraints::result,
		isMemberPointer = PtoMTraits::result
	};
	typedef typename PointerTraints::PointerType PointerType;
};


#endif

測試

 

void typetraits_test()
{
	const bool isPointer = TypeTraints::iterator>::isPointer;
}


 

 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved