Created
December 11, 2019 17:39
-
-
Save HanatoK/f489f782d6f54326e55d5d7aaa469519 to your computer and use it in GitHub Desktop.
C++17 std::any with std::map
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 <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