I'm trying to make a class (ParametersHolder
) that can contain different named parameters (Parameter<T>
). The ParametersHolder
has an std::unordered_map
container holding my parameters. To make this work, I had to derive Parameter<T>
from an empty ParameterBase
class and I dynamically cast ParameterBase
to Parameter<T>
when I want to get a parameter with the right type. Here is the code:
ParametersHolder.hpp
...
#include "Parameter.hpp"
class ParametersHolder {
std::unordered_map<std::string, std::shared_ptr<ParameterBase>> parameters;
public:
bool paramExists(std::string name) {
return parameters.find(name) != parameters.end();
}
template<typename T>
std::shared_ptr<Parameter<T>> getOrCreate(std::string name, int dims = 1) {
if (paramExists(name)) {
return getParam<T>(name);
}
return create<T>(name, dims);
}
template<typename T>
std::shared_ptr<Parameter<T>> create(std::string name, int dims = 1) {
if (paramExists(name)) throw std::runtime_error("Trying to create parameter '" + name + "' but it already exists");
auto param = std::make_shared<Parameter<T>>(dims);
parameters[name] = param;
return param;
}
template<typename T>
std::shared_ptr<Parameter<T>> getParam(std::string name) {
if (!paramExists(name)) throw std::runtime_error("Parameter '" + name + "' doesn't exist");
auto param = std::dynamic_pointer_cast<Parameter<T>>(parameters[name]);
if (param == nullptr) throw std::runtime_error("Parameter '" + name + "' is not a(n) " + boost::typeindex::type_id<T>().pretty_name());
return param;
}
};
Parameter.hpp
class ParameterBase {
public:
virtual ~ParameterBase() {}
};
template<typename T>
class Parameter : public ParameterBase {
std::vector<T> data;
public:
explicit Parameter(int dim = 1) : data(dim) {}
T getValue(int dim = 1) {
dimCheck(dim);
return data[dim - 1];
}
void setValue(T value, int dim = 1) {
dimCheck(dim);
data[dim - 1] = value;
}
private:
void dimCheck(int dim) {
if (dim > data.size()) {
auto errorMsg = "Trying to access dimension " + std::to_string(dim)
+ " but parameter has only " + std::to_string(data.size()) + " dimensions";
throw std::runtime_error(errorMsg);
}
}
};
To use this code I can do that:
auto paramsHolder = std::make_shared<ParametersHolder>();
auto filename = paramsHolder->create<std::string>("filename");
filename->setValue("untitled.txt");
...
auto param = paramsHolder->getParam<std::string>("filename");
std::cout << param->getValue() << std::endl;
This works fine but having an empty ParameterBase
feels odd. Is there another way to achieve that? I read about boost::any
, but I'm not sure this is the right use case. And if it is, I don't know what the type signature of the unordered_map
should be among these:
std::unordered_map<std::string, std::shared_ptr<Parameter<boost::any>>>
std::unordered_map<std::string, std::shared_ptr<boost::any>>
std::unordered_map<std::string, boost::any>
Aucun commentaire:
Enregistrer un commentaire