You could try this:
MyClass.h
class MyClass {
private:
static const std::map<key, value> m_myMap;
static const std::map<key, value> createMyStaticConstantMap();
public:
static std::map<key, value> getMyConstantStaticMap( return m_myMap );
}; //MyClass
MyClass.cpp
#include "MyClass.h"
const std::map<key, value> MyClass::m_myMap = MyClass::createMyStaticConstantMap();
const std::map<key, value> MyClass::createMyStaticConstantMap() {
std::map<key, value> mMap;
mMap.insert( std::make_pair( key1, value1 ) );
mMap.insert( std::make_pair( key2, value2 ) );
// ....
mMap.insert( std::make_pair( lastKey, lastValue ) );
return mMap;
} // createMyStaticConstantMap
With this implementation your classes constant static map is a private member and can be accessible to other classes using a public get method. Otherwise
since it is constant and can not change, you can remove the public get method
and move the map variable into the classes public section. I would however leave the createMap method private or protected if inheritance and or polymorphism is required. Here are some samples of use.
std::map<key,value> m1 = MyClass::getMyMap();
// then do work on m1 or
unsigned index = some predetermined value
MyClass::getMyMap().at( index ); // As long as index is valid this will
// retun map.second or map->second value so if in this case key is an
// unsigned and value is a std::string then you could do
std::cout << std::string( MyClass::getMyMap().at( some index that exists in map ) );
// and it will print out to the console the string locted in the map at this index.
//You can do this before any class object is instantiated or declared.
//If you are using a pointer to your class such as:
std::shared_ptr<MyClass> || std::unique_ptr<MyClass>
// Then it would look like this:
pMyClass->getMyMap().at( index ); // And Will do the same as above
// Even if you have not yet called the std pointer's reset method on
// this class object.
// This will only work on static methods only, and all data in static methods must be available first.
I had edited my original post, there was nothing wrong with the original code in which I posted for it compiled, built and ran correctly, it was just that
my first version I presented as an answer the map was declared as public and the map was const but wasn't static.
v = k + 'a' - 1
. – Lamb