lundi 31 août 2015

converting C# static class with constructor to standard C++11 [duplicate]

This question already has an answer here:

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 <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"});
  }
}

However this throws error when compiled:

$ g++ -std=c++11 test1.cpp /tmp/ccE3dKa6.o: In function Service::Strings::init()': test1.cpp:(.text+0x30): undefined reference toService::Strings::stringIDs' test1.cpp:(.text+0x6c): undefined reference to `Service::Strings::stringIDs' collect2: error: ld returned 1 exit status

Some my question is

1) how to I get this reference defined 2) is there a better way to replicate this design pattern in C++

Aucun commentaire:

Enregistrer un commentaire