Last active
September 2, 2016 13:48
-
-
Save davidalbertonogueira/81c8f9068c57f5d98c74071a2602232b to your computer and use it in GitHub Desktop.
Define and initialize static variable in header file using a singleton approach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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