LearnFrenzy
Sign in Take a free test

Modern C++ Features (C++11 to C++23) · Modern C++ Programs · Question 2

JSON-like value type with std::variant and recursion in C++ Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links