类型萃取
(图比代码思路清晰)
#include <iostream>
using namespace std;
struct TrueType
{};
struct FalseType
{};
template<class T>
struct TypeTraits
{
typedef FalseType IsPODType;
};
template<>
struct TypeTraits<int>
{
typedef TrueType IsPODType;
};
template<>
struct TypeTraits<char>
{
typedef TrueType IsPODType;
};
template<class T>
void _Copy(const T* src, T* dest, size_t size, FalseType)
{
cout<<"FalseType:"<<typeid(T).name()<<endl;
for(size_t i = 0; i < size; ++i)
{
dest[i] = src[i];
}
}
template<class T>
void _Copy(const T* src, T* dest, size_t size, TrueType)
{
cout<<"TrueType:"<<typeid(T).name()<<endl;
memcpy(dest, src, sizeof(T)*size);
}
template<class T>
void Copy(const T* src, T* dest, size_t size)
{
cout<<"Type:"<<typeid(T).name()<<endl;
_Copy(src, dest, size, TypeTraits<T>:: IsPODType());
}
int main()
{
string s1 [] = {"1", "2", "3" , "444444"};
string s2 [sizeof(s1)/sizeof(s1[0])];
Copy(s1, s2, sizeof(s1)/sizeof(s1[0]));
int a1 [10] = {1,2,3};
int a2 [10] = {0};
Copy(a1, a2, 10);
return 0;
}