#include <iostream>
#include <string>
using namespace std;
struct FalseType
{
static bool Get()
{
return false;
}
};
struct TrueType
{
static bool Get()
{
return true;
}
};
template<class T>
struct TypeTraits
{
typedef FalseType PODTYPE;
};
template<>
struct TypeTraits<int>
{
typedef TrueType PODTYPE;
};
template<>
struct TypeTraits<char>
{
typedef TrueType PODTYPE;
};
template<>
struct TypeTraits<double>
{
typedef TrueType PODTYPE;
};
template<>
struct TypeTraits<float>
{
typedef TrueType PODTYPE;
};
template<class T>
void Copy(T* dst, const T* src, size_t size)
{
// T是否为内置类型--通过类模板的特化来实现的
if (TypeTraits<T>::PODTYPE::Get())
{
// memcpy是浅拷贝
memcpy(dst, src, sizeof(T)*size);
}
else
{
for (size_t i = 0; i < size; ++i)
dst[i] = src[i];
}
}
int main()
{
int array1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int array2[sizeof(array1) / sizeof(array1[0])];
Copy(array2, array1, sizeof(array1) / sizeof(array1[0]));
string str1[] = { "1111", "2222", "3333", "4444" };
string str2[4];
Copy(str2, str1, sizeof(str1) / sizeof(str1[0]));
return 0;
}
C++中判断类型是否为内置类型
猜你喜欢
转载自blog.csdn.net/virgofarm/article/details/81143684
今日推荐
周排行