Skip to content

Instantly share code, notes, and snippets.

@nathiss
Last active November 3, 2017 10:48
Show Gist options
  • Save nathiss/5d4e2d8e0eecf9d01399d23559f102fb to your computer and use it in GitHub Desktop.
Save nathiss/5d4e2d8e0eecf9d01399d23559f102fb to your computer and use it in GitHub Desktop.
Associative array in C++17 for storing any data.
#include "settings_bag.h"
std::shared_ptr<SettingsBag> SettingsBag::instance = nullptr;
SettingsBag::SettingsBag() {
}
std::shared_ptr<SettingsBag> SettingsBag::Instance() {
if(instance == nullptr)
instance.reset(new SettingsBag());
return instance;
}
#ifndef SETTINGS_BAG_H
#define SETTINGS_BAG_H
#include <unordered_map>
#include <memory>
#include <string>
#include <any>
class SettingsBag {
public:
template <class T>
const T& Get(const std::string&) const;
template <class T>
void Set(const std::string&, const T&);
static std::shared_ptr<SettingsBag> Instance();
protected:
SettingsBag();
private:
std::unordered_map<std::string, std::any> bag;
static std::shared_ptr<SettingsBag> instance;
};
template <class T>
const T& SettingsBag::Get(const std::string& key) const {
return std::any_cast<const T&>(bag.at(key));
}
template <class T>
void SettingsBag::Set(const std::string& key, const T& value) {
bag[key] = std::make_any<const T&>(value);
}
#endif // SETTINGS_BAG_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment