模版类做基类,编译失败:无法解析的标记
文件如下:
CachedObj.h:
#ifndef CACHED_OBJ_H
#define CACHED_OBJ_H
#include <string>
using namespace std;
template <typename T>
class CachedObj{
private:
static T* freeSpace;
static allocator<T> memAlloc;
static void addToFreeList(T*);
static const size_t chunk = 0;
protected:
T *next;
public:
void* operator new(size_t);
void operator delete(void*,size_t);
virtual ~CachedObj();
};
template <typename T>
void CachedObj<T>::addToFreeList(T *t){
t->CachedObj<T>::next = freeSpace;
freeSpace = t;
};
template <typename T>
void* CachedObj<T>::operator new(size_t size){
if(size!=sizeof(T))//不可适用于继承
{
throw runtime_error("CachedObj:wrong size of objsize");
}
if(!freeSpace){
T* arr = memAlloc.allocate(chunk);
for(size_t i=0;i!=chunk;++i){
addToFreeList(&arr[i]);
}
}
T *p = freeSpace;
freeSpace = freeSpace->CachedObj<T>::next;
return p;
};
template <typename T>
void CachedObj<T>::operator delete(void* p,size_t size){
if(p)
addToFreeList((T*)p);
};
/*init static members*/
template<typename T>
T* CachedObj<T>::freeSpace = 0;
template<typename T>
std::allocator<T> CachedObj<T>::memAlloc;
class TestCached:public CachedObj<TestCached>{
string me;
public:
TestCached():me(string("")){};
TestCached(string &str):me(str){};
};
#endif
#include <string>
#include "CachedObj.h"
using namespace std;
int main(){
int times = 0;
string x = "xc";
TestCached *p;
while (times!=100000){
p = new TestCached(x);
delete p;
}
system("pause");
return 1;
}