How to create a list of lists using the CList template class
Hi all,
I think the subject mostly says it all :-). I need to create a list of lists, and since the rest of the code is using the CList template class, I'd like to use it for that too if at all possible. However, I don't get how I could do this. Could anyone with more clue than me on this topic help me out?
Thanks in advance,
Maxime
Re: How to create a list of lists using the CList template class
Quote:
Originally posted by mux
Hi all,
I think the subject mostly says it all :-). I need to create a list of lists, and since the rest of the code is using the CList template class,
Too bad. If you used std::list<>, it would have been much easier to create a list of lists.
Quote:
I'd like to use it for that too if at all possible. However, I don't get how I could do this.
To create a CList of a CList you must inherit your own class from CList and provide a user-defined assignment operator. The reason for this is that the types that you place in CList must be assignable. In other words, this code isn't going to work:
Code:
#include <afxtempl.h>
int main()
{
CList<int, int> a;
CList<int, int> b;
//
a = b; // will not compile
}
Since you cannot assign CLists, you can't make CList's as types for a CList without providing an assignment operator. In the assignment operator, you have to write code that copies from one CList to another.
The other alternative, if you still want to use CList, is to create a CList of pointers to a CList. This will work, but then there is the extra overhead and maintenance of your code having to make sure that the pointers are valid, and allocated / destroyed correctly.
Code:
typedef CList<int, int> IntList;
typedef CList<IntList*, IntList*> CListOfIntList;
//...
IntList IL = new IntList;
//...
CListOfIntList CL;
CL.Add( IL );
The last alternative is to use the standard container classes:
Code:
#include <list>
std::list< std::list<int> > ListOfLists;
That's all you need to do to create a list of a list of ints. You don't need to provide an assignment operator, and you don't need to resort to pointers. That's why I mentioned that it is too bad you used CList.
Regards,
Paul McKenzie