proxygen
|
folly/dynamic.h
provides a runtime dynamically typed value for C++, similar to the way languages with runtime type systems work (e.g. Python). It can hold types from a predetermined set of types (ints, bools, arrays of other dynamics, etc), similar to something like boost::variant
, but the syntax is intended to be a little more like using the native type directly.
To use dynamic
, you need to be using gcc 4.6 or later. You'll want to include folly/dynamic.h
(or perhaps also folly/json.h
).
Here are some code samples to get started (assumes a using folly::dynamic;
was used):
Any operation on a dynamic requires checking at runtime that the type is compatible with the operation. If it isn't, you'll get a folly::TypeError
. Other exceptions can also be thrown if you try to do something impossible (e.g. if you put a very large 64-bit integer in and try to read it out as a double).
More examples should hopefully clarify this:
Explicit type conversions can be requested for some of the basic types:
For more complicated conversions, see DynamicConverter.
You can iterate over dynamic arrays as you would over any C++ sequence container.
You can iterate over dynamic maps by calling items()
, keys()
, values()
, which behave similarly to the homonymous methods of Python dictionaries.
You can find an element by key in a dynamic map using the find()
method, which returns an iterator compatible with items()
:
The original motivation for implementing this type was to try to make dealing with json documents in C++ almost as easy as it is in languages with dynamic type systems (php or javascript, etc). The reader can judge whether we're anywhere near that goal, but here's what it looks like:
Dynamic typing is more expensive than static typing, even when you do it in C++. ;)
However, some effort has been made to keep folly::dynamic
and the json (de)serialization at least reasonably performant for common cases. The heap is only used for arrays and objects, and move construction is fully supported. String formatting internally also uses the highly performant folly::to<>
(see folly/Conv.h
).
A trade off to keep in mind though, is that sizeof(folly::dynamic)
is 64 bytes. You probably don't want to use it if you need to allocate large numbers of them (prefer static types, etc).
Q. Why doesn't a dynamic string support begin(), end(), and operator[]?
The value_type of a dynamic iterator is dynamic
, and operator[]
(or the at()
function) has to return a reference to a dynamic. If we wanted this to work for strings, this would mean we'd have to support dynamics with a character type, and moreover that the internal representation of strings would be such that we can hand out references to dynamic as accessors on individual characters. There are a lot of potential efficiency drawbacks with this, and it seems like a feature that is not needed too often in practice.
Q. Isn't this just a poor imitation of the C# language feature?
Pretty much.