1. 程式人生 > >型別提升(Promotion Trait)

型別提升(Promotion Trait)

本節將用到上節https://blog.csdn.net/xunye_dream/article/details/83050031中實現的IfThenElse模板類,如果感興趣可以檢視該模板類的實現。

型別提升在多引數的函式中體現。如實現以計算兩個數之和的函式,而這兩數的和可能大於現有這樣數的型別或者要取這兩數型別的最大者。於是,就需要將現有型別進行提升,以使函式的返回值型別能夠容納計算出的結果。

下面是型別提升的程式碼實現(模板)。

//base template, choose T1, T2, void
template<typename T1, typename T2>
struct Promotion
{
	typedef typename IfThenElse<(sizeof(T1) > sizeof(T2)),
				T1,
				typename IfThenElse<(sizeof(T1) < sizeof(T2)),
					T2,
					void>::ResultT
				>::ResultT ResultT;
};

如果兩個型別完全相同,就需要對上述模板類進行特化。

//local specialization template
template<typename T>
struct Promotion<T, T>
{
	typedef T ResultT;
};