I am currently working with some config files, and I wanted to map options with configuration functions. So far, I have this working code:
std::unordered_map<std::string, void (Model::*)(int)> m_configMap =
{
{ "threshold", &Model::setThreshold }
};
Now, as you may very well notice, this approach would not work if the input parameters were different, so I thought of adding the a parser like so (with the Jsoncpp library):
std::unordered_map<stsd::string, std::tuple<void(Model::*)(std::any), std::any(Json::Value*)()>> m_configMap =
{
{ "threshold", {&Model::setThreshold, &Json::Value::asInt}}
};
Now, this did not work,as it was giving me an error in the brace initialiser list saying that it could not convert types. I didnt quite understand, so I tried an smaller example:
std::tuple<void(Model::*)(int), Json::Int (Json::Value::*)(void)> foo =
{&Model::setThreshold, &Json::Value::asInt };
And this is not working either. However, if I change the Json part for a string, it will work.
I am not sure of what is wrong with this, and I was wondering if someone saw something that I'm missing.
Thank you very much in advance
CodePudding user response:
Looks like you're not refering to an instance of Model, or the member function of Model is not static. I don't know about the JSON part but this should get you started. If you have questions let me know.
#include <iostream>
#include <functional>
#include <string_view>
#include <unordered_map>
struct Model
{
public:
void setTreshold(int value)
{
std::cout << "treshold set to " << value << "\n";
}
};
int main()
{
Model model;
// I prefer using string_view over string for const char* parameters
// I also prefer using std::function over function pointers
std::unordered_map<std::string_view, std::function<void(int)>> m_configMap
{{
// the function should refer to an instance of Model, so use a lambda
// not a direct function pointer
{"threshold", [&](int value) { model.setTreshold(value); } }
}};
auto fn = m_configMap["threshold"];
fn(42);
return 0;
}