4

In the boost.intrusive document, it mentions about using multiple containers to store in one object. However, there's no actual example, so I made my own. Is this the right way to do?

#include <boost/intrusive/list.hpp>
struct tag1;
class A:public list_member_hook<>, public list_member_hook<tag<tag1> >
{
}

typedef list_base_hook<tag<tag1> > TagHook;
typedef list<A> DefaultList;
typedef list<A, base_hook<TagHook> > TagList;

int main()
{
     DefaultList dList;
     TagList tList;
     A *a = new A();
     dList.push_back(a);
     tList.push_back(a);
}

If I add another container of the same type (such as adding another DefaultList), it will produce error. Is this intended? Why are we not allowed to use the second container of the same type?

Amumu
  • 17,924
  • 31
  • 84
  • 131

1 Answers1

3

You're close. Here's what it should look like:

#include <boost/intrusive/list.hpp>
struct tag1;
class A:public list_base_hook<>, public list_base_hook<tag<tag1> >
{
}

typedef list_base_hook<tag<tag1> > TagHook;
typedef list<A> DefaultList;
typedef list<A, base_hook<TagHook> > TagList;

int main()
{
     DefaultList dList;
     TagList tList;
     A *a = new A();
     dList.push_back(*a);
     tList.push_back(*a);
}

list_base_hook is used when you want to inherit the hook. list_member_hook is for when you want the hook to be a member. Also, push_back takes a reference, not a pointer.

Here's an example using member hooks:

#include <boost/intrusive/list.hpp>
class A
{
public:
    list_member_hook<> m_hook1, m_hook2;
}

typedef list<A, member_hook<A, list_member_hook<>, &A::m_hook1> > List1;
typedef list<A, member_hook<A, list_member_hook<>, &A::m_hook2> > List2;

int main()
{
     List1 list1;
     List2 list2;
     A *a = new A();
     list1.push_back(*a);
     list2.push_back(*a);
}
Cory Nelson
  • 29,236
  • 5
  • 72
  • 110
  • Ah I see. It should be pointer. So, we cannot declare something like DefaultList list1,list2 or List1 a,b,c right? Ty for the member hook. Now I know I can declare multiple containers inside the base class without inheritance and create tags. Seems better to use. – Amumu May 30 '11 at 10:59