Created
November 20, 2018 02:17
-
-
Save slwu89/8027db668b466d7f0ec4fe4b3bb7a8b2 to your computer and use it in GitHub Desktop.
stupid simple way to store heterogeneous parameters for c++ projects.
This file contains hidden or 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
/* standard includes */ | |
#include <stdio.h> | |
#include <iostream> | |
/* hash-table */ | |
#include <unordered_map> | |
#include <string> /* for keys */ | |
class parameters { | |
public: | |
/* constructor */ | |
parameters(const size_t n) : paramsI(n), paramsD(n) { | |
std::cout << "parameters born at " << this << std::endl; | |
}; | |
/* destructor */ | |
~parameters(){ | |
std::cout << "parameters dying at " << this << std::endl; | |
}; | |
/* delete copy constructor/assignment operator, default move constructor/assignment operator */ | |
parameters(const parameters&) = delete; | |
parameters& operator=(const parameters&) = delete; | |
parameters(parameters&&) = default; | |
parameters& operator=(parameters&&) = default; | |
/* assign a key-value pair */ | |
template <typename T> | |
void set_param(const std::string& key, const T val); | |
/* get a value by key */ | |
template <typename T> | |
T get_param(const std::string& key); | |
// double get_param(const std::string& key){ return params.at(key);}; | |
private: | |
std::unordered_map<std::string, double> paramsD; | |
std::unordered_map<std::string, int> paramsI; | |
}; | |
/* assign a key-value pair */ | |
template <> | |
inline void parameters::set_param<int>(const std::string &key, const int val){ | |
paramsI.insert(std::make_pair(key,val)); | |
}; | |
template <> | |
inline void parameters::set_param<double>(const std::string &key, const double val){ | |
paramsD.insert(std::make_pair(key,val)); | |
}; | |
/* get a value by key */ | |
template <> | |
inline double parameters::get_param<double>(const std::string &key){ | |
return paramsD.at(key); | |
} | |
template <> | |
inline int parameters::get_param<int>(const std::string &key){ | |
return paramsI.at(key); | |
} | |
#include <memory> | |
int main(int argc, const char * argv[]) { | |
std::unique_ptr<parameters> p_ptr = std::make_unique<parameters>(5); | |
p_ptr->set_param("dbl_p", 5.0); | |
p_ptr->set_param("int_p", 5); | |
double dbl_p = p_ptr->get_param<double>("dbl_p"); | |
int int_p = p_ptr->get_param<int>("int_p"); | |
std::cout << "dbl_p: " << dbl_p << " and size: " << sizeof(dbl_p) << std::endl; | |
std::cout << "int_p: " << int_p << " and size: " << sizeof(int_p) << std::endl; | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment