/*******************************************************
***** Quantin' Leap Ltd. **********
* Copyright (c) 2001, All Rights Reserved *
********************************************************/
#include "WU_Persistent.h"
#include "WU_Exception.h"
#include <string>
#include <map>
using std::string;
using std::map;
using std::less;
using std::pair;
using std::make_pair;
/*! map container with a string key*/
typedef map< string, WU_Persistent*, less<string> > maptype;
/*! map iterator */
typedef maptype::iterator mapiterator;
class WU_Container
{
public:
/*! default constructor*/
WU_Container();
/*! frees all the memory allocated for each WU_Persistent
component*/
~WU_Container();
//accessor functions
/*! Registers a component in the container.
Associates a component with an ID, and if the ID is
already present, throws an exception.
\param obj the component to be registered.
\param ID the key to identify the component.
*/
void registerComponent(WU_Persistent* obj,string ID);
/*! Retrieves a component from the container, identified
by ID. Returns a pointer to the component, or a null
pointer if ID is not found
\param ID the component key.
*/
WU_Persistent* retrieveComponent(string ID);
int getNumComponents() {return m_map.size();}
private:
/*! The STL map which associates components to ID strings*/
maptype m_map;
};
//implementation
WU_Container::WU_Container()
{}
WU_Container::~WU_Container()
{
mapiterator i = m_map.begin(),end = m_map.end();
while (i != end)
{
//deleting the WU_Persistent*
if ((*i).second) delete (*i).second;
i++;
}
}
inline void WU_Container::registerComponent
(WU_Persistent* obj,string ID)
{
pair<mapiterator,bool> P = m_map.insert(make_pair(ID,obj));
if (!P.second) //failed
{
WU_Exception ex
("failed to register component. The ID is already used",
"WU_Container::registerComponent");
throw ex;
}
}
inline WU_Persistent* WU_Container::retrieveComponent(string ID)
{
mapiterator i = m_map.find(ID);
if (i == m_map.end()) //not found
return 0;
else
return (*i).second;
}