c++中的类型萃取

17 篇文章 1 订阅
本文探讨了C++中引入类型萃取的原因,旨在提高程序效率。通过示例展示了在某些情况下,使用`memcpy`进行内存拷贝可能更高效,但对于包含指针的自定义类型,如`string`,需要采用成员变量逐个复制的方式。类型萃取使得在编译时能根据实际类型选择合适的方法,确保正确性和效率。
摘要由CSDN通过智能技术生成

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

看下边的一段代码:

template<typename T>
void SeqList<T>::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还能正确吗??

看图:


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

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

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

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

//内置类型结构体
struct __TrueType
{
	bool Get()
	{
		return true;
	}
};
//非内置类型结构体
struct __FalseType
{
	bool Get()
	{
		return false;
	}
};
template <typename T>
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 <class _Tp>
struct TypeTraits< _Tp*>
{
	typedef __TrueType __IsPODType;
};


下边给出copy函数的实现:

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

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

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

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值