64,654
社区成员
发帖
与我相关
我的任务
分享
#include "valuetypenullflag.h"
#include "ilist.h"
#pragma once
namespace Generic
{
template<class T> class ValueList : public IList
{
private:
T *m_array;
int m_count;
int m_arrayLength;
int m_index;
T m_flag;
public:
ValueList(T flag)
{
this->m_array = new T[4];
this->m_arrayLength = 4;
this->m_index = -1;
this->m_flag = flag;
for (int i = 0 ;i < 4; i++)
{
this->m_array[i] = this->m_flag ;
}
}
~ValueList(void)
{
}
public:
int Count() const
{
for(int i = 0 ; i < this->m_arrayLength ; i ++)
{
if(this->m_array[i] == this->m_flag)
{
return i ;
}
}
return this->m_arrayLength;
}
int ArrayLength() const { return m_arrayLength; }
public:
int Add(T item)
{
bool canAdd = false;
for (int i = 0;i< this->m_arrayLength;i++)
{
if(this->m_array[i] == this->m_flag)
{
canAdd = true;
this->m_array[i] = item;
return i;
}
}
if(!canAdd)
{
int i = this->ExtendArray();
this->m_array[i] = item;
return i;
}
return -1;
}
T GetItem(int index)
{
return this->m_array[index];
}
private:
int ExtendArray()
{
int originalArrayLength = this->m_arrayLength;
T *cloneArray = this->m_array;
this->m_array = new T[this->m_arrayLength * 2];
//memset(this->m_array,0,sizeof(int) * this->m_arrayLength * 2);
for(int i = 0 ; i < this->m_arrayLength * 2 ; i++)
{
this->m_array[i] = this->m_flag;
}
this->m_count = this->m_arrayLength;
for (int i = 0; i < this->m_arrayLength; i++)
{
this->m_array[i] = cloneArray[i];
}
this->m_arrayLength *= 2;
return originalArrayLength;
}
};
}
能否统一类型调用呢?
例如
IList *m_list = new ValueList<int>();
IList *m_list = new ValueList<double>();
类似这种写法 ?
class IList
{
public:
template<class T>
int Add(T item)
{
ValueList<T>* vlist = dynamic_cast<ValueList<T>*>(this);
if (!vlist)
return false;
return vlist->Add(item);
}
template<class T>
T GetItem(int index)
{
ValueList<T>* vlist = dynamic_cast<ValueList<T>*>(this);
if (!vlist)
return false;
return vlist->GetItem(item);
}
};
template<class Type>
class ValueList : IList
{
public:
};
#include "valuelist.h"
#include <string>
#pragma once
using namespace Generic;
using namespace std;
enum ArrayTypes
{
Int = 0,
Double = 1,
};
_declspec(dllexport) class List
{
private:
IList *m_intList;
IList *m_doubleList;
public:
List(ArrayTypes type)
{
int typeId = (int)type;
switch(typeId)
{
case 0:
m_intList = new ValueList<int>(-2147483648);
break;
case 1:
m_doubleList = new ValueList<double>(2.22507e-308);
break;
default:
break;
}
}
~List(void)
{
delete []this->m_intList;
delete []this->m_doubleList;
}
int Add(int item)
{
int index = m_intList->Add(item);
return index;
}
int Add(double item)
{
int index = m_doubleList->Add(item);
return index;
}
int GetItem(int index)
{
return this->m_intList->GetItem(index);
}
};