How to initialize a static map member in a cpp file body

  • Thread starter Thread starter Bill Sun
  • Start date Start date
B

Bill Sun

Hi,

I have a question about to initialize a static map member like this:

In the mapclass.h;
class mapclass
{
private:
static map<string, int> s_mapArray;
}

In the mapclass.cpp;
.....
s_mapArray["Item01"] = 0;
s_mapArray["Item02"] = 1;
.....

I don't want to initialize this static member in a member function body, I only want to initialize it in the cpp file body.
What I can do ?

Thanks advanced,

Bill
 
You can't do what you want directly - the're no initializer syntax for something like a map.

What you can do is create another class to help you..

// in mapclass.h
class mapclass
{
private:
friend class maploader;
map<string,int> s_mapArray;
};

// In mapclass.cpp
#include "mapclass.h"

map<string,int> mapclass::s_mapArray;

class mapLoader
{
public:
mapLoader()
{
mapclass::s_mapArray["Item01"] = 0;
mapClass::s_mapArray["Item02"] = 1;
// ...
}
};

static mapLoader loader(mapClass::s_mapArray);

-cd


Hi,

I have a question about to initialize a static map member like this:

In the mapclass.h;
class mapclass
{
private:
static map<string, int> s_mapArray;
}

In the mapclass.cpp;
....
s_mapArray["Item01"] = 0;
s_mapArray["Item02"] = 1;
....

I don't want to initialize this static member in a member function body, I only want to initialize it in the cpp file body.
What I can do ?

Thanks advanced,

Bill
 
Hi,

I have a question about to initialize a static map member like this:

In the mapclass.h;
class mapclass
{
private:
static map<string, int> s_mapArray;
}

In the mapclass.cpp;
....
s_mapArray["Item01"] = 0;
s_mapArray["Item02"] = 1;
....

I don't want to initialize this static member in a member function body, I only want to initialize it in the cpp file body.
What I can do ?

Thanks advanced,

Bill
I think this may be covered by the upcoming assignment library which is due in the next version? of boost. See www.boost.org.

Jeff F
 
Bill Sun said:
Hi,

I have a question about to initialize a static map member like this:

In the mapclass.h;
class mapclass
{
private:
static map<string, int> s mapArray;
}

In the mapclass.cpp;
....
s mapArray["Item01"] = 0;
s mapArray["Item02"] = 1;
....

I don't want to initialize this static member in a member function body,
I only want to initialize it in the cpp file body.
What I can do ?

// One of the few possible solutions.

class CMyMapInitializer
{
public:
CMyMapInitializer(map<string, int> &myMap)
{
myMap["Item01"] = 0;
myMap["Item02"] = 1;
}
};

map<string, int> mapclass::s_mapArray;

CMyMapInitializer mapInitializer(mapclass::s_mapArray);

// other mapclass definitions .....


-hth.
-Vinayak
 
Back
Top