Here's my code and the error, and below I'll show some code that works.
#include <iostream>
#include <string>
#include <nlohmann/json.hpp>
using JSON = nlohmann::json;
using std::cout;
using std::endl;
using std::string;
template <class ObjectType>
void dump(const JSON &json) {
for (auto &[key, value]: json.items()) {
string foo = value.get<std::string>();
cout << "Key: " << key;
cout << " Value: " << foo << endl;
}
}
int main(int, char **) {
JSON json;
json["alpha"] = "beta";
dump<string>(json);
}
-$ g++ -std=c++17 Foo.cpp -o Foo && Foo
Foo.cpp: In function ‘void dump(const JSON&)’:
Foo.cpp:14:37: error: expected primary-expression before ‘>’ token
14 | string foo = value.get<std::string>();
| ^
Foo.cpp:14:39: error: expected primary-expression before ‘)’ token
14 | string foo = value.get<std::string>();
| ^
If I comment out the template
line and change the call in main to dump(json)
, everything works.
My real problem is actually inside a template class, not a template function, but this is the most simplified version I could create. What I really want is this line:
ObjectType obj = value.get<ObjectType>();
But that would be the next step.
Does anyone know what I'm doing wrong and how to fix it?