Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidalbertonogueira/81c8f9068c57f5d98c74071a2602232b to your computer and use it in GitHub Desktop.
Save davidalbertonogueira/81c8f9068c57f5d98c74071a2602232b to your computer and use it in GitHub Desktop.
Define and initialize static variable in header file using a singleton approach
//header file
struct MyStruct {
public:
const std::unordered_map<std::string, uint32_t> str_to_int{
{ "a", 1 },
{ "b", 2 },
//...
{ "z", 26 }
};
const std::unordered_map<int , std::string> int_to_str{
{ 1, "a" },
{ 2, "b" },
//...
{ 26, "z" }
};
std::string some_string = "justanotherstring";
uint32_t some_int = 42;
static MyStruct & Singleton() {
static MyStruct instance;
return instance;
}
private:
MyStruct() {};
};
//Usage in cpp file
int main(){
std::cout<<MyStruct::Singleton().some_string<<std::endl;
std::cout<<MyStruct::Singleton().some_int<<std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment