Upgrade to Pro — share decks privately, control downloads, hide ads and more …

JSON, std::variant, and you

JSON, std::variant, and you

Presented at the Triangle C++ Developers meetup on 10 January 2017.

C++17 introduces many new features, one of which is `std::variant`, a type whose instances can hold any one of a listed range of types. This seems a great fit for JSON, which has just null, booleans, doubles, strings, arrays, and objects.

This presentation, which was mostly a code demo and less of a slideshow, explored techniques I used to implement a JSON parser and pretty-printer using `std::variant`. Spoiler: CRTP was involved.

Chris Jester-Young

January 10, 2017
Tweet

More Decks by Chris Jester-Young

Other Decks in Programming

Transcript

  1. Code > slides • Please feel free to check out

    the code at https://gitlab.com/cky/cpp17-json • The slides here are just summary notes so you can spend all your time playing with the code instead ☺ ◦ You need to apply the fix at http://stackoverflow.com/a/32004040/13 before the tests, or anything using the UTF-16/UTF-32 modes, will compile
  2. What is a variant? • A variant is a type

    that can hold objects of various types ◦ E.g., variant<int, string, vector<map<string, string>>> • A variant remembers its current type ◦ Retrieve with get<T>(v) ◦ Test with get_if<T>(&v)
  3. So how is it different from any? • All possible

    types known ◦ No dynamic allocation ◦ Visitation possible
  4. Comparison with Boost.Variant • Multi-level visitation! • In-place construction, emplace()

    • monostate • No built-in recursive type wrapper ◦ Use CRTP instead, or perhaps make your own wrapper
  5. Visitation: it’s what’s for dinner • The clean way to

    do different things for different types • Just define operator() that accepts each type ◦ Can be member functions as well as template functions, or mix and match ◦ Can use enable_if to shape your dispatch however you like • Variadic visit() means multiple dispatch
  6. Current implementations • As of current writing, most readily available

    in Visual Studio 2017 RC • libc++ 4.0 and libstdc++ 7.0 will also have it, but for now you have to build it yourself • MPark.Variant is written by libc++’s std::variant implementer and provides a backport to C++14
  7. Questions? You can find c++17-json at https://gitlab.com/cky/cpp17-json. • Email me

    at [email protected] with any questions, or tweet me at @cky944 • I camp out on Stack Overflow, as well as #stackoverflow on freenode • https://github.com/cky, https://gitlab.com/cky Thanks for coming to my talk! ❤