C++之类型萃取技巧

 

使用类型萃取的原因

就是当你的顺序表是自定义类型,我们进行顺序表增容的时候,这个时候会出现一个问题,比如string类型,这个类型中有一个_buf与_ptr,当储存少于16个的时候这时会储存在_buf当中的,如果多于16个,那个会单独开辟空间,进行储存,这时拷贝的时候就是拷贝过去这个储存的地址而已,所以这样调用析构函数的时候,当增加容量的时候,这个时候会把储存string的那块空间进行释放。会造成数据丢失的问题。
 

这里写图片描述

所以,在这里面我们提到一个类型萃取的技巧,可以把自定义类型和内置类型的区分开,然后对自定义类型的使用for循环拷贝,对于内置类型的,采用memcpy的方式进行拷贝


#include<iostream>
#include<stdlib.h>

using namespace std;


//类型萃取
struct __truetype
{
    bool get()
    {
        return true;
    }
};

struct __falsetype
{
    bool get()
    {
        return false;
    }

};


template<typename T>

struct typetraits
{
    typedef __falsetype __ispodtype;

};

template<>
struct typetraits<int >
{
    typedef __truetype __ispodtype;
};

template<>
struct typetraits<char >
{
    typedef __truetype __ispodtype;
};

template<>
struct typetraits<short >
{
    typedef __truetype __ispodtype;
};

template<>
struct typetraits<bool >
{
    typedef __truetype __ispodtype;
};
template<>
struct typetraits<unsigned int >
{
    typedef __truetype __ispodtype;
};
template<>
struct typetraits<unsigned short >
{
    typedef __truetype __ispodtype;
};
template<>
struct typetraits<unsigned long >
{
    typedef __truetype __ispodtype;
};
template<>
struct typetraits<long >
{
    typedef __truetype __ispodtype;
};
template<>
struct typetraits<long long >
{
    typedef __truetype __ispodtype;
};
template<>
struct typetraits<unsigned long long >
{
    typedef __truetype __ispodtype;
};

template<>
struct typetraits<long double >
{
    typedef __truetype __ispodtype;
};
template<>
struct typetraits<double >
{
    typedef __truetype __ispodtype;
};

template<>
struct typetraits<float >
{
    typedef __truetype __ispodtype;
};



template<typename T>
void Copy(const T*src, T* dst, size_t size)
{
    if (typetraits<T>::__ispodtype().get())
    {
        cout << "__truetype:" << typeid(T).name() << endl;
        memcpy(dst, src, size*sizeof(T));

    }
    else
    {
        cout << "__falsetype:" << typeid(T).name() << endl;
        for (size_t i = 0; i < size; i++)
        {
            dst[i] = src[i];
        }
    }

}


void test()
{
    int a1[8] = { 1, 2, 3, 4, 5, 6 };
    int a2[8] = { 9, 5, 6, 7, 8, 2, 2 };
    Copy(a1, a2, 3);
    cout << a2<<endl;

    string c1[10] = {"123","7989465","456321","4561","4563"};
    string c2[5] = {"654","312","a"};
    Copy(c1, c2, 3);




}
int main()
{

    test();
    system("pause");
    return 0;
}

在这里我们采用了模板的特化,这里使用了全特化,直接给int,double等内置类型做特化。

在这里我们设定内置类型是truetype,设置自定义类型是falsetype,然后我们通过不同的类型利用get()函数返回不同的布尔值,这样对内置类型采用memcp拷贝,对于非内置类型,采用for循环拷贝,这样就能实现我们想要的结果了。
 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值