Define a Value that can be null, bool, number, string or a list of Values using std::variant, and write a recursive to_string with std::visit.
Solution
main.cpp
#include <iostream>
#include <string>
#include <variant>
#include <vector>
struct Value;
using List = std::vector<Value>;
struct Value {
std::variant<std::nullptr_t, bool, double, std::string, List> data;
};
template <typename... Fs> struct overloaded : Fs... { using Fs::operator()...; };
std::string to_string(const Value& v) {
return std::visit(overloaded{
[](std::nullptr_t) -> std::string { return "null"; },
[](bool b) -> std::string { return b ? "true" : "false"; },
[](double d) -> std::string { auto s = std::to_string(d); s.erase(s.find_last_not_of('0') + 1); if (s.back() == '.') s.pop_back(); return s; },
[](const std::string& s) -> std::string { return '"' + s + '"'; },
[](const List& l) -> std::string {
std::string out = "[";
for (std::size_t i = 0; i < l.size(); ++i) out += (i ? ", " : "") + to_string(l[i]);
return out + "]";
},
}, v.data);
}
int main() {
Value doc{List{Value{std::string("Asha")}, Value{21.0}, Value{true}, Value{nullptr},
Value{List{Value{91.5}, Value{88.0}}}}};
std::cout << to_string(doc) << '\n';
return 0;
}
Output Verified by compiling and running
["Asha", 21, true, null, [91.5, 88]]
A variant can contain a vector of the type being defined (vector allows incomplete types), giving a recursive data structure. overloaded combines lambdas into one visitor.
More Modern C++ Features (C++11 to C++23) practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!