how to define a static member in a template class
i have trouble to define a static member in a template, and i search from google, but didn't find any similar case, my case is a little complex, i paste the code below.
code in xxx.h Code:
template <class T> class FreeListManager Code:
template<class T> list<T*> Code:
template<class CLASSA> list<CLASSA*> i was told FreeListManager<CLASSA> and FreeListManager<CLASSB> are totally two different class, why does the redefinition error come out? i also try Code:
list<CLASSA*> FreeListManager<CLASSA>::freeList; can someone help me, really appreciate your help. denny |
Are you sure that you want to use static? This means that there is only one instance of the data member; controlled by the class. Should you wish to create two instances of FreeListManager with the same template parameter then you will lose the second list.
|
But to address your question first note that for templates the definition and the declaration need to be in the same header file.
I would suggest that you make your lists pointers, thus you will have: Code:
static list<T*> *freeList; Code:
template<class T> list<T*> *FreeListManager<T>::freeList = 0; |
sure, that's what i want, the code was download from opendiameter project, it can be compiled by very old version gcc complier.
but i found it cannot compliled by gcc-4.1.2. yes, i include the xxx.h file in the xxx.cpp file. As i know, FreeListManager is a only template, and FreeListManager<CLASSA> is actual class, and FreeListManager<CLASSB> is another one, i want to define two static list member for both class,FreeListManager<CLASSA>::freeList, FreeListManager<CLASSB>::freeList, so the two static member should be not one instance, but two. Just like what i tested Code:
template <class T> class FreeListManager the result is FreeListManager<CLASSA>::counter=2 FreeListManager<CLASSB>::counter=3 so it seem there are two static variable FreeListManager<CLASSA> and FreeListManager<CLASSB> |
i also tried
template<> list<CLASSA> FreeListManager<CLASSA>::freeList; template<> list<CLASSA> FreeListManager<ACLASSA>::usedList; template<> list<CLASSB> FreeListManager<CLASSB>::freeList; template<> list<CLASSB> FreeListManager<CLASSB>::usedList; i aslo got undefined reference error |
for the gcc compiler "the definition and the declaration need to be in the same header file." That's NOT include the header file in a source but actually placed in the header file.
|
All times are GMT -5. The time now is 05:47 AM. |