c++中的类型萃取

为什么会引入类型萃取??提高程序效率~~~

看下边的一段代码:

template
void SeqList::CheckCapacity(int count)
{
	if (_sz + count >= _capacity)
	{
		int NewCapacity = 2 * _sz + 1;
		T *tmp = new T[NewCapacity];
		//memcpy(tmp,_pdata,sizeof(T)*_sz);
		/*int i = 0;
		for (i = 0;i < _sz;i++)
		{
			tmp[i] = _pdata[i];
		}*/
		Copy(tmp,_pdata,_sz);
		delete[] _pdata;
		_pdata = tmp;
		_capacity = NewCapacity;
	}
}


这是一个模板函数,//屏蔽的部分和/* */屏蔽的部分实现的都是是内存的拷贝,看着

memcpy的效率高一点,这的是这样吗??要是T是string,memcpy还能正确吗??

看图:

c++中的类型萃取_第1张图片

所以,一般的类型(比如int,float,double,char等)进行复制的时候采用memcpy效

率会高一些;而像string或者是其他的一些自定义类型(并且成员有指针类型的话),一

个一个复制才是正确的方法。

下边给出类型萃取的代码:

//内置类型结构体
struct __TrueType
{
	bool Get()
	{
		return true;
	}
};
//非内置类型结构体
struct __FalseType
{
	bool Get()
	{
		return false;
	}
};
template 
struct TypeTraits
{
	typedef __FalseType __IsPODType;
};
//内置类型的特化
template <>
struct TypeTraits< bool>
{
	typedef __TrueType __IsPODType;
};

template <>
struct TypeTraits< char>
{
	typedef __TrueType __IsPODType;
};
template <>
struct TypeTraits< unsigned char >
{
	typedef __TrueType __IsPODType;
};
template <>
struct TypeTraits< short>
{
	typedef __TrueType __IsPODType;
};
template <>
struct TypeTraits< unsigned short >
{
	typedef __TrueType __IsPODType;
};
template <>
struct TypeTraits< int>
{
	typedef __TrueType __IsPODType;
};
template <>
struct TypeTraits< unsigned int >
{
	typedef __TrueType __IsPODType;
};
template <>
struct TypeTraits< long>
{
	typedef __TrueType __IsPODType;
};
template <>
struct TypeTraits< unsigned long >
{
	typedef __TrueType __IsPODType;
};
template <>
struct TypeTraits< long long >
{
	typedef __TrueType __IsPODType;
};
template <>
struct TypeTraits< unsigned long long>
{
	typedef __TrueType __IsPODType;
};
template <>
struct TypeTraits< float>
{
	typedef __TrueType __IsPODType;
};
template <>
struct TypeTraits< double>
{
	typedef __TrueType __IsPODType;
};
template <>
struct TypeTraits< long double >
{
	typedef __TrueType __IsPODType;
};
template 
struct TypeTraits< _Tp*>
{
	typedef __TrueType __IsPODType;
};


下边给出copy函数的实现:

template
void Copy(T*tmp, T*_pdata,int _sz)
{
	if (TypeTraits::__IsPODType().Get())
	{
		memcpy(tmp, _pdata, sizeof(T)*_sz);
	}
	else
	{
		int i = 0;
		for (i = 0;i < _sz;i++)
		{
			tmp[i] = _pdata[i];
		}
	}
}

我们不能说一定要选择某一种办法,而应该是选择最正确的方法,就像memcpy效率再

高,对于string类型还是不能实现。选择正确的方法,然后在正确的方法中选择最好的。

关于类型萃取,就写这么多。

你可能感兴趣的:(c++,c/c++)