模板——类型萃取

模板——类型萃取

类型萃取,在STL中用到的比较多,用于判断一个变量是否为POD类型(平凡类型)。
简单来说可以用来判断出某个变量是内置类型还是自定义类型。 通过类型萃取,萃取到变量类型,对不同变量进行不同处理,以提升程序的效率。
应用场景:
在拷贝对象时,对于内置类型我们用memcpy来进行赋值( 浅拷贝相关的类也可以通过memcpy赋值 )。 对于自定义类型,且大多数深拷贝的对象来说,我们必须通过调用for循环赋值语句来赋值.
我们如果可以判断出它是POD类型或者非POD类型的话。这样, 对于POD类型用memcpy函数,对于非POD用赋值,这样就能提高程序的效率。
下面我用图来解释一下推演的过程:

代码如下:
#include<string>
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<>
struct __TypeTraits<double>
{
          typedef __TrueType IsPODType;
};

template<class T>
T* __TypeCopy(T* dst, const T* src, size_t n, __TrueType)
{
          cout << "memcpy" << endl;
          return (T*)memcpy(dst, src, n*sizeof(T));
}

template<class T>
T* __TypeCopy(T* dst, const T* src, size_t n, __FalseType)
{
          cout << "operator=" << endl;
          for (size_t i = 0; i < n; i++)
          {
                   dst[i] = src[i];
          }
          return dst;
}

template<class T>
T* TypeCopy(T* dst, const T* src, size_t n)
{
          return __TypeCopy(dst, src, n, __TypeTraits<T>::IsPODType());
}

//测试
void TestTypeTraits()
{
          int a1[3] = { 1, 2, 3 };
          int a2[3] = { 0, 0, 0 };
          TypeCopy(a1, a2, 3);

          string s1[] = { "11", "22", "33" };
          string s2[] = { "0", "0", "0" };
          TypeCopy(s1, s2, 3);

          char c1[3] = { 'a' ,'b', 'c'};
          char c2[3] = { 'x', 'y', 'z' };
          TypeCopy(c1, c2, 3);

          double d1[3] = { 1.0, 2.0, 3.0 };
          double d2[3] = { 0.0, 0.0, 0.0 };
          TypeCopy(d1, d2, 3);
}


猜你喜欢

转载自blog.csdn.net/ling_hun_pang_zi/article/details/79827939