类型萃取实现顺序表

#include <iostream>

#include<string>

using namespace std;

struct TrueType

{

bool get()

{

return true;

}


};

struct FalseType

{

bool get()

{

return false;

}


};

template <typename T>

struct TypeTraits

{

typedef FalseType istPodType;

};

template<>

struct TypeTraits<int>

{

typedef TrueType isPodType;

};

template<typename T>

class Seqlist

{

private:

T *_data;

int _size;

int _capacity;

public:

Seqlist()

:_size(0)

, _capacity(3)

{

_data = new T[_capacity];

}

~Seqlist()

{

if (_data != NULL)

{

delete[]_data;

_data = NULL;

}

}

void CheakCapacity()

{

if (_size == _capacity)

{

if (TypeTraits<T>::isPodType().get())

{

T * tem = new T[_capacity];

memcpy(tem, _data, sizeof(T)*_capacity);

delete[]_data;

_data = tem;

_capacity = 2 * _capacity + 3;

}

else 

{

T * tem = new T[_capacity];

int i = 0;

for (i = 0; i < _size; i++)

{

tem[i] = _data[i];

}

delete[]_data;

_data = tem;

_capacity = 2 * _capacity + 3;

}

}

}

void PushBack(const T &d)

{

CheakCapacity();

_data[_size] = d;

_size++;

}

void print()

{

int i = 0;

for (i = 0; i < _size; i++)

cout << _data[i] << " ";

}

};


int main()

{

Seqlist<int> s;

s.PushBack(1);

s.PushBack(2);

s.PushBack(3);

s.PushBack(4);

s.print();

getchar();

return 0;

}

2.类型萃取实现copy函数

#include <iostream>

#include<string>

using namespace std;

struct TrueType

{

bool get()

{

return true;

}


};

struct FalseType

{

bool get()

{

return false;

}


};

template <typename T>

struct TypeTraits

{

typedef FalseType istPodType;

};

template<>

struct TypeTraits<int>

{

typedef TrueType isPodType;

};

template <typename T>

void copy(T *dest, const T *src,int size, TrueType)

{

cout << typeid(T).name() << endl;

memcpy(dest, src, size*sizeof(T));

}

template <typename T>

void copy(T *dest, const T *src, int size, FalseType)

{

cout << typeid(T).name() << endl;

int i = 0;

for (i = 0; i < size; i++)

dest[i] = src[i];

}

int main()

{

int arr1[] = { 1, 2, 3, 4, 5 };

int i = 0;

int  arr2[6] = { 0 };

int size1 = sizeof(arr1) / sizeof(arr1[0]);

copy<int>(arr2, arr1,size1, TypeTraits<int>::isPodType());

for (i = 0; i < size1; i++)

cout << arr2[i] << " ";

getchar();

return 0;

}