Skip to content

Instantly share code, notes, and snippets.

@HanatoK
Created December 11, 2019 17:39
Show Gist options
  • Save HanatoK/f489f782d6f54326e55d5d7aaa469519 to your computer and use it in GitHub Desktop.
Save HanatoK/f489f782d6f54326e55d5d7aaa469519 to your computer and use it in GitHub Desktop.
C++17 std::any with std::map
#include <map>
#include <string>
#include <any>
#include <iostream>
std::map<std::string, std::any> ParameterMap;
template <typename T>
bool set_params(const std::string& name, const T& var, bool add_new_key = false) {
if (ParameterMap.count(name) > 0 || add_new_key) {
ParameterMap[name.c_str()] = var;
return true;
} else {
return false;
}
}
template <typename T>
bool get_params(const std::string& name, T& var) {
for (auto it = ParameterMap.begin(); it != ParameterMap.end(); ++it) {
if (name.compare(it->first) == 0) {
var = std::any_cast<T>(it->second);
return true;
}
}
return false;
}
int main() {
std::string path{"path.dat"};
double lowerBound = -10;
double upperBound = 10;
set_params("pathFile", path, true);
ParameterMap["lowerBoundary"] = lowerBound;
ParameterMap["upperBoundary"] = upperBound;
std::string strS;
get_params("pathFile", strS);
std::cout << strS << std::endl;
set_params("pathFile", std::string{"path2.dat"});
get_params("pathFile", strS);
std::cout << strS << std::endl;
double x;
get_params("lowerBoundary", x);
std::cout << x << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment