//类型萃取
#include<iostream>
using namespace std;
struct __TrueType
{
bool Get()
{
return true;
}
};
struct __FalseType
{
bool Get()
{
return false;
}
};
template <class _Tp>
struct TypeTraits
{
typedef __FalseType __IsPODType; //不是内置类型则为 __FALSETYPE
};
//内置类型全部特化
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;
};
template<typename T>
void Copy(const T* src, T* dst, size_t size)
{
if (TypeTraits <T>::__IsPODType().Get() == 0) //不是内置类型
{
cout << "赋值运算符重载" << endl;
for (size_t i = 0; i < size; ++i)
{
dst[i] = src[i];
}
}
else
{
cout << "使用memcpy()" << endl;
memcpy(dst, src, size*sizeof(T));
}
}
void Test1()
{
string s1[10] = { "1", "2", "3", "4444444444444444444444444" };
string s2[10] = { "11", "22", "33" };
Copy(s1, s2, 10);
Copy(s1, s2, 10);
int a1[10] = { 1, 2, 3 };
int a2[10] = { 0 };
Copy(a1, a2, 10);
Copy(a1, a2, 10);
}
int main()
{
Test1();
system("pause");
return 0;
}