Created
January 30, 2022 06:58
-
-
Save SealtielFreak/715a7dee9ef838c5eb457d9f181abf5f to your computer and use it in GitHub Desktop.
This file contains 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
#include <iostream> | |
#include <string> | |
#include <map> | |
#include <thread> | |
#include <functional> | |
#include <forward_list> | |
#include <cstdio> | |
typedef std::map<std::string, void*> MemoryState; // map is no optimized, need a forward_list | |
template<typename TypeValue> | |
auto insertValueState(MemoryState &container, const std::string &name, TypeValue *value) -> void { | |
container.insert(std::pair(name, static_cast<void*>(value))); | |
} | |
template<typename TypeValue> | |
auto getValueState(MemoryState &container, const std::string &name) -> TypeValue { | |
return *static_cast<TypeValue*>(container[name]); | |
} | |
template<typename TypeValue> | |
auto getReferenceValueState(MemoryState &container, const std::string name) -> TypeValue { | |
return static_cast<TypeValue>(container[name]); | |
} | |
auto clearMemoryState(MemoryState &container) -> void { | |
for(auto &[k, v]: container) { | |
std::free(v); | |
v = nullptr; // optional and unnecessary | |
} | |
container.clear(); | |
} | |
auto main() -> int { | |
MemoryState memoryState; | |
insertValueState(memoryState, "value", new int(3)); | |
insertValueState(memoryState, "hello", new std::string("Hello world, I'm a string!")); | |
insertValueState(memoryState, "func", new std::function([] { std::printf("Hello world from lambda\n"); })); | |
insertValueState(memoryState, "thread", new std::thread([] { std::printf("Hello world from thread\n"); })); | |
std::printf("%s\n", getValueState<std::string>(memoryState, "hello").data()); | |
int value = getValueState<int>(memoryState, "value"); | |
getValueState<std::function<void(void)>>(memoryState, "func")(); | |
getReferenceValueState<std::thread*>(memoryState, "thread")->join(); | |
clearMemoryState(memoryState); | |
return value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment