0

Based on Bearvine's answer here Static constructor in c++

I've taken the following C# code:

namespace Services
{
    internal static class Strings
    {
        private static Dictionary<uint, string> stringIDs = new Dictionary<uint, string>(0x2);

        static Strings()
        {
            stringIDs.Add(0x1, "String1");
            stringIDs.Add(0x2, "String2");
        }
    }
}

And in C++

#include <iostream>
#include <unordered_map>
#include <string>

namespace Service
{
  class Strings
  {
  private:
    static std::unordered_map<unsigned int,std::wstring> stringIDs;

  public:
    static void init (void);
  };


  void Strings::init() 
  {
    stringIDs.insert({0x1, L"String1"});
    stringIDs.insert({0x2, L"String2"});
  }
}

std::unordered_map<unsigned int,std::wstring> Service::Strings::stringIDs;

int main()
{
  Service::Strings::init();
  // program etc
  return 0;
}

Question - is this the best way to replicate this .NET design pattern in C++ ? Or would you recommend an alternate class design when migrating code to C++?

Community
  • 1
  • 1
Malcolm McCaffery
  • 2,468
  • 1
  • 22
  • 43
  • Removed the 1st question that was duplicate, and left the 2nd question. – Malcolm McCaffery Sep 01 '15 at 05:53
  • 1
    In general I'd avoid init() methods, too easy to forget or to call twice when code grows. Several options in C++, two are easiest I can think about: a static method with lazy initialization (exposing a getter instead of underlying implementation) or a singleton with instance in implementation file. – Adriano Repetti Sep 01 '15 at 06:49

0 Answers0