You can try the following:
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.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 persistent static class maps are private members and can be accessed by other classes using the public get method. Otherwise, since it is constant and cannot be changed, you can remove the public get method and move the map variable to the public section of the classes. However, I would leave the createMap method private or protected if inheritance and / or polymorphism is required. Here are some examples 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 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 edited my original post, there was nothing wrong with the source code in which I posted it, compiled, built and worked correctly, it was just my first version, which I submitted as an answer, was declared as public, and the map was const, but was not static.
Francis Cugler Mar 17 '15 at 15:38 2015-03-17 15:38
source share