C++ - Initializing a static map as a private class member
#include <map>
#include "Color.h"
enum COLOR
{
RED = 0, BLUE, GREEN, YELLOW, ORANGE, WHITE, BLACK,
BRICKS_FROM_A_DISTANCE_ON_AN_UNUSUALLY_SUNNY_AFTERNOON,
// etc
COLOR_COUNT
};
class ColorManager
{
typedef std::map<COLOR, Color> ColorMap;
public:
ColorManager();
Color getColor(COLOR color) const;
private:
static ColorMap createColorMap();
static ColorMap colorMap;
};
// in some .cpp file:
ColorManager::ColorMap ColorManager::createColorMap()
{
ColorMap ret;
// populate ret
return ret;
}
ColorManager::ColorMap ColorManager::colorMap = ColorManager::createColorMap();
Or with C++11:
#include <map>
#include "Color.h"
enum COLOR
{
RED = 0, BLUE, GREEN, YELLOW, ORANGE, WHITE, BLACK,
BRICKS_FROM_A_DISTANCE_ON_AN_UNUSUALLY_SUNNY_AFTERNOON,
// etc
COLOR_COUNT
};
class ColorManager
{
using ColorMap = std::map<COLOR, Color>;
public:
ColorManager();
Color getColor(COLOR color) const;
private:
static ColorMap colorMap;
};
// in some .cpp file:
ColorManager::ColorMap ColorManager::colorMap = []
{
ColorMap ret;
// populate ret
return ret;
}();
std::map has a constructor that takes a pair of iterators as arguments, so you could initialize the map with, for example, an array of pairs:
#include "Color.h"
#include <map>
enum COLOR { RED = 0, BLUE, GREEN, YELLOW, ORANGE, WHITE, BLACK,
BRICKS_FROM_A_DISTANCE_ON_AN_UNUSUALLY_SUNNY_AFTERNOON,
// etc
COLOR_COUNT };
class ColorManager
{
public:
ColorManager();
~ColorManager();
Color getColor(COLOR color) const;
private:
typedef std::map<COLOR, Color> ColorMap;
static ColorMap colorMap;
};
using std::make_pair;
using std::pair;
std::pair<COLOR, Color> colorPairs[] = {make_pair(RED, Color(...)),
make_pair(BLUE, Color(...)),
make_pair(GREEN, Color(...)),
...};
ColorManager::ColorMap ColorManager::colorMap(colorPairs, colorPairs + COLOR_COUNT);
In C++0x, you will be able to simply do this:
ColorManager::ColorMap ColorManager::colorMap({{RED, Color(...)},
{BLUE, Color(...)},
{GREEN, Color(...)},
...});