I have a template function specified:
template<class T> void jsonParse(json_object* jobj, eParseWhat parseWhat, T &value) {
...
if(parseWhat == PARSE_UID) {
value = json_object_getInt(val);
}
if(parseWhar == PARSE_EMAIL) {
value = json_object_getString(val);
}
...
}
Now when I want to parse the uid
of the json-object I call the method with an int
:
json_object* obj = ...;
int uid = 0;
jsonParse(obj,PARSE_UID,uid);
But then a compile error occurs at the assignment in line:
value = json_object_getString(val);
Because of the call with an int
the compiler thinks that the type of the variable value
is int
and json_object_getString(val)
returns const char*
. So the compiler says:
can not convert from const char* to int
.
Have you got any suggestion to solve this problem?
Why are you even using a template if you are going to do a switch statement of a bunch of if statements for each type? Your template instantiation will never compile if you want to treat every type as multiple types. This design is flawed but if you must then you can use specializations to accomplish something similar.
template<class T> void jsonParse(json_object* jobj, eParseWhat parseWhat, T &value) {
static_assert(false); // not a handled type
}
template<> void jsonParse(json_object* jobj, eParseWhat parseWhat, int &value) {
value = json_object_getInt(val);
}
template<> void jsonParse(json_object* jobj, eParseWhat parseWhat, std::string &value) {
value = json_object_getString(val);
}
As GMan points out it is usually preferable to overload functions rather than specialize a function template. The equivalent using an overloaded function would be something like this:
void jsonParse(json_object* jobj, eParseWhat parseWhat, int &value) {
value = json_object_getInt(val);
}
void jsonParse(json_object* jobj, eParseWhat parseWhat, std::string &value) {
value = json_object_getString(val);
}