Re: Problem using STL list and map objects as static member variables
Bit byte wrote:
I am writing a small parser object. I need to store keywords etc in
lsts. Because this data is to be shared by all instances of my parser
class, I have declared the variable as class variables (i.e. statics).
//declarations in parser class (private section)
static list<string> m_keywords, m_symbols_used;
static map<string, myParser::FuncData> m_mapped_funcs ;
I have initialization code like this:
m_symbols_used.clear();
//loadup keywords
m_keywords.clear()
m_keywords.push_back(ABC) ;
m_keywords.push_back(CDE) ;
...
I obviously can't place this in the constructor since they are statics -
(actually, I tried but I had linkage errors). Any ideas as to how to
initialize these variales ?
Use an initializer helper class:
class A
{
public:
// ...
private:
static const std::map<int,const char*> map_;
};
Then in your .cpp file:
namespace // anonymous
{
template<class Key, class Value>
class MapInitializer
{
std::map<Key,Value> m_;
public:
operator std::map<Key,Value>() const { return m_; }
MapInitializer& Add( const Key& k, const Value& v )
{
m_[k] = v;
return *this;
}
};
}
const std::map<int,const char*> A::map_
= MapInitializer<int,const char*>()
.Add( 10, "Msg 1" )
.Add( 20, "Msg 2" )
.Add( 30, "Msg 3" );
Cheers! --M