Skip to content

Instantly share code, notes, and snippets.

@SealtielFreak
Created January 30, 2022 06:58
Show Gist options
  • Save SealtielFreak/715a7dee9ef838c5eb457d9f181abf5f to your computer and use it in GitHub Desktop.
Save SealtielFreak/715a7dee9ef838c5eb457d9f181abf5f to your computer and use it in GitHub Desktop.
#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