1. 程式人生 > >模板之型別萃取

模板之型別萃取

函式類模板萃取主要針對的是含有自定義型別的函式
***我們的型別函式如果需要拷貝往往可以通過給定庫函式經行萃取,但是尼?***我們的型別函式型別中每一個變數中含有的成員個數都是不知道的,我們就需要另外一種拷貝深拷貝的方式,對我們的自定義型別經行處理。
好了,我們定義一種不需要傳遞第三引數的方法型別萃取一下。

定義自定義型別和內建型別

	// 代表內建型別 
struct TrueType 
{   
	static bool Get() 
	{
		return true ;  
	}
};

	// 代表自定義型別 
struct FalseType 
{
	static bool Get() 
	{
		return false ; 
	}
}; 

分類特化一下,每一種型別認為有區別都進行特化一下


template<class T> 
struct TypeTraits 
{
	typedef FalseType   IsPODType; 
};
template<> 
struct TypeTraits<char>
{
	typedef TrueType     IsPODType;
};

template<>
struct TypeTraits<short> 
{
	typedef TrueType     IsPODType; 
};

template<> struct TypeTraits<int>
{
	typedef TrueType     IsPODType;
};

template<> 
struct TypeTraits<long> 
{
	typedef TrueType     IsPODType;
};

copy拷貝物件確定實際型別

template<class T> 
void Copy(T* dst, const T* src, size_t size)
{
	if (TypeTraits<T>::IsPODType::Get())    
		memcpy(dst, src, sizeof(T)*size);
	else    {
			for (size_t i = 0; i < size; ++i) 
				dst[i] = src[i];
	}
}

新增各種型別變數測試一下

int main()
{
	int a1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; 
	int a2[10]; 
	Copy(a2, a1, 10);  
	string s1[] = { "1111", "2222", "3333", "4444" };
	string s2[4]; 
	Copy(s2, s1, 4);    
	return 0;
}


在這裡插入圖片描述
在這裡插入圖片描述
自定義型別和內建型別的拷貝萃取都沒有什麼問題