Search code examples
c++staticinitializationmultimap

Initialize static multimap class member


I'm need a static member from the type multimap

I checked that static members must be initialized (or defined) after the class declaration

The problem is that I'm not finding the correct sintax to initialize (define) the multimap that I declared

Here is my multimap declaration:

 namespace sctg
 {
        class Buffer : public BufferInterface
        {
           public:
                  ...
           private:

                  static std::multimap<std::string, std::pair<sc_core::sc_time, sc_core::sc_time> >    timeStampPackets; 
       };
 }

I'm using C++98.


Solution

  • If all you want to do is define it, not add any members to it, then you just say:

    std::multimap<std::string, std::pair<sc_core::sc_time, sc_core::sc_time> > Buffer::timeStampPackets;
    

    outside the class definition, in the .cpp file for the class. That's it!

    But life will be simpler if you use a typedef for the map type:

    namespace sctg
    {
      class Buffer : public BufferInterface
      {
      public:
        //  ...
      private:
        typedef std::multimap<std::string, std::pair<sc_core::sc_time, sc_core::sc_time> > TimeStampMap;
    
        static TimeStampMap  timeStampPackets;   // declare
      };
    }
    

    In .cpp file:

    namespace sctg
    {
      Buffer::TimeStampMap Buffer::timeStampPackets;  // define
    }
    

    If you want to insert a member into the map ...

    If you're using C++11 you can initialize the member like this:

    TimeStampMap Buffer::timeStampPackets{ { {}, { sc_core::sc_time_stamp(), sc_core::sc_time_stamp() } } };
    

    If you can't use C++11 then the best alternative is:

    TimeStampMap Buffer::timeStampPackets = getTimeStampPackets();
    

    Where that function returns the map containing the data you want:

    TimeStampMap getTimeStampPackets()
    {
      TimeStampMap result;
      result.insert( TimeStampMap::value_type("", std::pair<sc_core::sc_time, sc_core::sc_time>()) );
      return result;
    }