    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Dynamic C++ (Part 2)</title>
        <link>https://members.accu.org/index.php/articles/1841</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #116 - August 2013</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c328/">o116</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-328/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+328/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Dynamic C++ (Part 2)</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 02 August 2013 18:04:56 +01:00 or Fri, 02 August 2013 18:04:56 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Previously we saw how to use some simple dynamic features in C++. Alex Fabijanic and Richard Saunders explore more powerful dynamic tools.</p>
<p><strong>Body:</strong>&nbsp;<p class="quote">[Y]ou canâ€™t build a system that is completely statically typed.</p>
<p class="quote">~ Bjarne Stroustrup [<a href="#[Venners04]">Venners04</a>]</p>

<p>In this installment of the â€˜Dynamic C++â€™ series of articles, we continue to explore the dynamic solutions in C++ language. We start with <strong>Boost</strong> <code>type_erasure</code> [<a href="#[Boost.TypeErasure]">Boost.TypeErasure</a>], a combination of <code>Boost.Any</code> [<a href="#[Boost.Any]">Boost.Any</a>] and <code>Boost.Function</code> [<a href="#[Boost.Function]">Boost.Function</a>], addressing the C++ runtime polymorphism shortcomings. Next, we look into <code>Val</code>, a class at the heart of the <strong>PicklingTools</strong> library [<a href="#[PicklingTools]">PicklingTools</a>] aimed at interaction with Python environments. We conclude with <strong>Facebook</strong>â€™s <strong>folly</strong> library solution for interfacing the world of web and JSON from C++ â€“ the <code>dynamic</code> class.</p>

<h2>Boost.TypeErasure</h2>

<p>According to the author, <code>type_erasure</code> is a generalization of <code>Boost.Any</code> and <code>Boost.Function</code> classes, allowing easy composition of arbitrary type erased operations; it addresses the shortcomings of C++ runtime polymorphism, in particular:</p>

<ul>
	<li>intrusiveness</li>
	<li>dynamic memory management</li>
	<li>inability to apply multiple independent concepts to a single object.</li>
</ul>

<p>Library uses some advanced constructs such as concepts and template metaprogramming constructs from <code>boost::mpl</code>. In a similar fashion to <code>boost::variant</code> specifying a set of types at construction time that can be contained at runtime, the <code>type_erasure</code> library specifies at construction time a set of operations that can be performed on it at runtime. This is achieved through a vector of <em>concepts</em> provided at object declaration site as shown in Listing 1 for an <code>incrementable</code> and <code>ostreamable</code> object.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
any&lt;
    mpl::vector&lt;
        copy_constructible&lt;&gt;,
        typeid_&lt;&gt;,
        incrementable&lt;&gt;,
        ostreamable&lt;&gt;
    &gt;
&gt; x(10);
++x; // incrementable
std::cout &lt;&lt; x &lt;&lt; std::endl; // ostreamable
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>In the example, <code>copy_constructible</code> allows <em>copying</em> and <em>destruction</em> of the object, while<code>typeid_</code> provides <em>run-time type information</em> so that <code>any_cast</code> can be used; these effectively make <code>type_erasure any</code> equivalent to <code>any</code> [<a href="#[Boost.Any]">Boost.Any</a>]. Additionally, <code>incrementable</code> and <code>ostreamable</code> concepts are specified, allowing incrementing and streaming of the value <code>x</code>. Operations can have arguments, so replacing <code>incrementable</code> <em>concept</em> with <code>addable</code> allows adding of two <code>any</code>â€™s. The functionality is brittle in a subtle way, though â€“ while adding two values of different types will compile, unfortunately it results in undefined behaviour at runtime. This problem can be alleviated by specifying <code>relaxed_match</code> concept (according to author, recently renamed to a more appropriate <code>relaxed</code> name), which causes exception to be thrown. The proper way of dealing with this problem is using <em>placeholders</em>, as shown in Listing 2.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
int array[5];

typedef mpl::vector&lt;
    copy_constructible&lt;_a&gt;,
    copy_constructible&lt;_b&gt;,
    typeid_&lt;_a&gt;,
    addable&lt;_a, _b, _a&gt;
&gt; requirements;

tuple&lt;requirements, _a, _b&gt; t(&amp;array[0], 2);
any&lt;requirements, _a&gt; x(get&lt; 0 &gt; (t) +
  get&lt; 1 &gt;(t));
// x now holds array + 2
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>Placeholders are used extensively throughout the library. A placeholder is a substitute for a template parameter in a concept. The library automatically replaces all placeholders with the actual wrapped types.</p>

<p>Furthermore, <code>type_erasure</code> supports references (both <code>const</code> and non-<code>const</code>), as well as user-defined <em>concepts</em>. Listing 3 demonstrates adding <code>stringable</code> <em>concept</em> to <code>type_erasure</code>, allowing a <code>to_string()</code> member function call syntax directly on an <em>integer</em> value wrapped in <code>any</code>. Things can be simplified when implementation and interface are the same (i.e. a member of <code>type_erasure::any</code> called <code>to_string</code> calls a <code>to_string</code> member of the contained type), <code>BOOST_TYPE_ERASURE_MEMBER</code> â€˜shortcutâ€™ macro can be used.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template&lt;class F, class T&gt;
struct to_string
{
  // conversion function
  static T apply(const F&amp; from, T&amp; to)
  {
    return to = NumberFormatter::format(from);
  }
};
namespace boost {
namespace type_erasure {
  template&lt;class F, class T, class Base&gt; 
  // binding
  struct concept_interface
     &lt;::to_string&lt;F, T&gt;, Base, F&gt; : Base
  {
    typedef 
       typename rebind_any&lt;Base, T&gt;::type IntType;
    T to_string(IntType arg = IntType())
    {
      return call(::to_string&lt;C, T&gt;(),
                  *this, arg);
    }
}; }
typedef any&lt;to_string&lt;_self, std::string&gt;,
   _self&amp;&gt; stringable;
int i = 123;
stringable s(i);
std::string str = s.to_string(); // s == &quot;123&quot;

			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<p>Internally, a <code>void*</code> <em>pointer</em> points to the held heap-allocated value and a static equivalent of <em>virtual table</em> serves as a <em>binding</em> for attached operations as shown in Listing 4.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
// storage
struct storage
{
    storage() {}
    template&lt;class T&gt;
    storage(const T&amp; arg) : data(new T(arg)) {}
    void* data;
};
// binding of concept to actual type
typedef ::boost::type_erasure::binding&lt;Concept&gt; table_type;
// actual storage
::boost::type_erasure::detail::storage data;
                           table_type table;
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>

<p>Boost.Type erasure is an interesting and valuable â€˜mergerâ€™ of <code>any</code> and <code>function</code> features, providing dynamic-language like features within the confines of standard C++. Implementation is rather complex and use has some non-intuitive weak spots that can quickly get an inexperienced user in serious trouble. A more robust interface (even if only with <code>_typedef_</code>s provided for most frequently used types) would greatly improve the usability and safety for less experienced users.</p>

<h2>PicklingTools Val</h2>

<p>The next reviewed solution to the dynamic typing problem is the <strong>PicklingTools</strong> [<a href="#[PicklingTools]">PicklingTools</a>] Val [<a href="#[Saunders1]">Saunders1</a>], [<a href="#[Saunders2]">Saunders2</a>], [<a href="#[Saunders3]">Saunders3</a>]. The <strong>PicklingTools</strong> library is an open-source library made up of Python, C++ and Java code allowing cross language communication. The <strong>PicklingTools</strong> evolved from a need to allow Python and C++ to share Python dictionaries across language boundaries. Many modern applications are built using multiple languages: Python, C++, Java, JavaScript, Lua, Icon/Unicon. The front-end languages (JavaScript, Python, Lua) tend to be dynamic languages for handling scripting and basic data flow. The back-end languages (C++, C, Java, FORTRAN) handle the heavy-lifting of fast communications, data I/O and CPU intensive work. In these hybrid systems, front-end languages need to communicate with the back-end languages intensively. Dictionaries, supported in some form by most dynamic languages, became the <em>currency</em> of many systems. The <strong>PicklingTools</strong> library solution focuses on the Python dictionary and C++.</p>

<table class="sidebartable">
	<tr>
		<td class="title">The Val Name Rationale</td>
	</tr>
	<tr>
		<td>Why Val and not something like dynamic or any? Three reasons:
			<ul>
				<li>Everything is, in general, passed by value</li>
				<li><strong>PicklingTools</strong> encourage use of valgrind to help ensure quality</li>
				<li>Val is only three letters, which is closer to a dynamic language with no letters for the type.</li>
			</ul>
		</td>
	</tr>

</table>

<p>While making Python dictionaries easy to express in C++ was not a primary goal, given how much users enjoyed the ease of use, the C++ PicklingTools embraced them wholeheartedly. The goal, then, became to make Python dictionaries as easy to express in C++ as they are in Python.</p>

<p>Consider the ease of a dynamic dictionary manipulation in Python shown in Listing 5.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
# Create a Python literal
&gt;&gt;&gt; d = { 'a': 1, 'b':2.2, 'c': 
...{ 'X':1, 'Y':[1,2,3]  }}

&gt;&gt;&gt; print d['a']   # lookup a single key: 'a' -&gt; 1
&gt;&gt;&gt; d['b'] = 3.3   # insert into dict

# Also easy to lookup/insert nested entities
&gt;&gt;&gt; print d['c']['X']   # lookup nested key
&gt;&gt;&gt; d['c']['Y'] = 0     # insert nested
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 5</td>
	</tr>
</table>

<p>Because C++ is a statically-typed language, it requires a compile-time type for all variables. <strong>PicklingTools</strong> use Val to indicate a dynamic value.</p>

<p>A side-by-side comparison of basic dynamic typing in Python and C++ using Val is shown in Listing 6.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
# Python
&gt;&gt;&gt; a = 1
&gt;&gt;&gt; a = 2.2
&gt;&gt;&gt; a = 'three'    # a takes three different types

// C++
Val a = 1;         // overload constructor
a = 2.2;           // overload op=
a = &quot;three&quot;;
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 6</td>
	</tr>
</table>

<p>The <strong>PicklingTools</strong> Val is implemented as a <em>union</em> and a <em>type-tag</em>, where the value is constructed using <em>placement new</em> inside the <em>union</em>. The destructor has to manually notice which type to destruct (for non-POD types) and explicitly call the correct constructor. The Val is really just a dynamic container, with storage as shown in Listing 7. C++11 standard introduces <code>alignof</code>/<code>alignas</code> to address alignment concerns; in pre-C++11, although standard does not explicitly guarantee it and some experts discourage it [<a href="#[GotW28]">GotW28</a>], a union with a <code>double</code> member is practically close enough guarantee of the alignment to the largest member of the union.</p>

<p>As can be concluded from Listing 7, by design <code>Val</code> can only contain certain types, shown in Listing 8.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
struct Val
{
  // Flags: the ascii typetag, subtype for arrays,
  char tag;
  char subtype;
  char isproxy;
  char pad;

  Allocator *a;  // if using shared memory or
                 // special allocator

  union
  {
    int_1  s;      // type tag 's'
    int_u1 S;      // type tag 'S'
    int_2  i;      // type tag 'i'
    int_u2 I;      // type tag 'I'
    int_4  l;      // type tag 'l'
    int_u4 L;      // type tag 'L'
    int_8  x;      // type tag 'x'
    int_u8 X;      // type tag 'X'
    real_4 f;      // type tag 'f'
    real_8 d;      // type tag 'd'
    complex_8  F;  // type tag 'F'
    complex_16 D;  // type tag 'D'
    char t[sizeof(Tab)]; 
                   // type tag 't', usually 32
    char n[sizeof(Arr)];
                   // type tag 'n', usually 32
  } u;
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 7</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
// POD types
int_1, int_u1, int_2, int_u2,
int_4, int_u4, int_8, int_u8,
real_4, real_8,
complex_8, complex_16, size_t

// Non-POD types
string, None, Tab (like Python dictionary),
Arr (like Python list)
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 8</td>
	</tr>
</table>

<p>There are no-user defined types by design. This allows library writers to concentrate on making the interface for C++ Python dictionaries as close to Python as possible without worrying about the problems generality brings.</p>

<p>Listing 9 shows how easy it is to construct a <code>Val</code> from basic types and get values out by means of user-defined conversion.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
// overload Val constructor on all supported types
Val a = 1;
Val b = 2.2;
Val c = &quot;three&quot;;
// Get a value out via user-defined conversions
int_u4 i = a;
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 9</td>
	</tr>
</table>

<p>The user-defined conversions and overloading are syntactic sugar. Of course, overloaded cast operators direct calls are really just taking advantage of â€˜syntactic sugarâ€™ for function calls as shown below:</p>

<pre class="programlisting">
  Val v = 1;
  int_u4 i = v.operator int_u4();
</pre>
  
<p>The <code>Val</code> supports user-defined conversions for all basic types. If the conversion isnâ€™t direct, then the user-defined conversions follow the <em>Principle of Least Surprise</em>: convert as C++ would (example below).</p>

<pre class="programlisting">
  Val v = 3.14159265;
  int_u4 i4 = v; // Which conversion?  As C++ would:
     // int_u4 i4 = static_cast&lt;int_u4&gt;(3.14159265);
</pre>

<p>If the conversion doesnâ€™t make sense, behaviour is identical to that in Python â€“ an exception is thrown, see Listing 10.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
# Python
&gt;&gt;&gt; a = 3.14159265
&gt;&gt;&gt; i4 = int(a)      # converts to 3
&gt;&gt;&gt; d = dict(a)      # Exception!  doesn't make
                     # sense to convert to dict

// C++
Val a = 3.14159265;
int_u4 i4 = a;       // converts to 3
Tab d = i4;          // Compile-time error, can't
                     // construct Tab from float
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 10</td>
	</tr>
</table>

<p>The <code>Val</code> provides the basic container to support dynamic dictionaries. The C++ <code>Tab</code> is equivalent to the Python <code>dict</code> (think <code>Tab == Table</code>). The keys of the C++ <code>Tab</code>, aswell as the values of the dictionary are <code>Val</code>â€™s, allowing us to construct dynamic dictionaries:</p>

<pre class="programlisting">
  # PythonId-1007573&quot;&gt;
  d = {'a':1, 'b':2.2, 'c':'three'}

  // C++
  Tab d = &quot;{'a':1, 'b':2.2, 'c':'three'}&quot;;
</pre>

<p>Note that the C++ literal is inside a string: the library overloads the constructor of the <code>Tab</code> to take a string which contains the literal. While C++11 has some great new literal constructs, it canâ€™t quite mimic Pythonâ€™s syntax.</p>

<p>Literal construction of a Python dictionary is supported using exactly the Python syntax: you can cut-and-paste the Python dictionary literal and paste it into the C++ quotes. There is a little Python dictionary parser embedded in the <code>Tab</code> class so that it recognizes the same syntax. Rather than invent a new syntax for literal construction, library leverages the well-known Python syntax.</p>

<h2>Facebook folly::dynamic</h2>

<p>The Facebook <code>folly::dynamic</code> [<a href="#[Folly.Dynamic]">Folly.Dynamic</a>] class is another one in the spectrum of dynamic-typing classes. The class aims to relax the static typing constraints, especially in the <em>JSON</em> format data manipulation scenarios; it 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 (ints, bools, arrays of other dynamics, etc), similar to <code>boost::variant </code>and <strong>PicklingTools</strong> <code>Val</code>, but the syntax is intended to be more akin to using the native type directly.</p>

<table class="sidebartable">
	<tr>
		<td class="title">Facebook String Flavour</td>
	</tr>
	<tr>
		<td>Facebook <code>folly::fbstring</code> is a drop-in replacement for <code>std::string</code>, providing the benefit of significantly increased performance on virtually all important primitives. This is achieved by using a three-tiered storage strategy and cooperating with the memory allocator; <code>fbstring</code> is designed to detect use of jemalloc [<a href="[#jemalloc]">jemalloc</a>] and cooperate with it to significantly improve speed and memory usage.
		<p><strong>Storage strategies</strong></p>
		<ul>
			<li>Small strings (&lt;=23 chars) are stored in-situ without memory allocation.</li>
			<li>Medium strings (24-255 chars) are stored in malloc-allocated memory and copied eagerly.</li>
			<li>Large strings (&gt;255 chars) are stored in malloc-ated memory and copied lazily.</li>
		</ul>
		<p><strong>Implementation highlights</strong></p>
		<ul>
			<li>Compatible with <code>std::string</code>.</li>
			<li>Thread-safe, reference-counted copy-on-write for large (&gt;255 chars) strings.</li>
			<li>Uses malloc instead of allocators.</li>
			<li>Jemalloc-friendly</li>
			<li>The <code>find()</code> is implemented using Boyer-Moore [<a href="[#Wikipedia]">Wikipedia</a>].</li>
			<li>Offers conversions to and from <code>std::string</code>.</li>
			</ul>
		<p>Supported architectures are x86 and x64; porting fbstring to big-endian architectures would require changes.</p>
		</td>
	</tr>

</table>

<p>An example of creating a <code>dynamic</code> holding most common types is shown below. Strings are stored internally as <code>fbstring</code>, the Facebook drop-in replacement for <code>std::string</code>.</p>

<pre class="programlisting">
  dynamic twelve = 12;
  dynamic str = &quot;string&quot;;   // fbstring
  dynamic nul = nullptr;
  dynamic boolean = false;
</pre>

<p>The library extensively uses C++11 features for both speed and syntactic advantages. For example, as shown in Listing 11, arrays can be initialized with <em>initializer lists</em>. This particular feature, however, also imposes a limitation â€“ <code>dynamic</code> has no default constructor. The rationale for this design decision is due to the standard requirement for the expression <code>dynamic d = {}</code> to call default constructor. The conflict arises in the default construction either having to result in <code>d.isArray()</code> (a) being <code>false</code> for the expression <code>dynamic d = {}</code> or (b) being <code>true</code> for <code>dynamic d</code>. The solution the authors of <code>folly::dynamic</code> deemed most appropriate is to entirely disallow the default construction.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
dynamic array = {
  &quot;array &quot;, &quot;of &quot;, 4, &quot; elements&quot; };
assert(array.size() == 4);
dynamic emptyArray = {};
assert(array.empty());
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 11</td>
	</tr>
</table>

<p>Maps from dynamics to dynamics are called objects. As shown in Listing 12, the <code>dynamic::object</code> constant is how an empty map fromdynamics to dynamics is created. The same listing also shows how <code>dynamic</code> objects can be created by using <code>object::operator()</code>.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
dynamic map = dynamic::object;
map[&quot;something&quot;] = 12;
map[&quot;another_something&quot;] = map[&quot;something&quot;] * 2;
dynamic map2 = dynamic::object
  (&quot;something&quot;, 12)(&quot;another_something&quot;, 24);
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 12</td>
	</tr>
</table>

<p>The internal <code>dynamic</code> storage is shown in Listing 13. Types that can be held are: <code>null</code>, <code>Array</code>, <code>bool</code>, <code>double</code>, <code>integer</code> (64-bit), <code>Object</code> and <code>String</code>.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
enum Type
{
  NULLT,
  ARRAY,
  BOOL,
  DOUBLE,
  INT64,
  OBJECT,
  STRING,
};
// ...
Type type_;
union Data
{
  explicit Data() : nul(nullptr) {}
  void* nul;    // void* used instead of
                // std::nullptr_t due to gcc bug
  Array array;
  bool boolean;
  double doubl;
  int64_t integer;
  fbstring string;
  typename std::aligned_storage&lt;
    sizeof(std::unordered_map&lt;int,int&gt;),
    alignof(std::unordered_map&lt;int,int&gt;)
  &gt;::type objectBuffer;
} u_;
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 13</td>
	</tr>
</table>

<p>Examples of object and string construction are shown in Listing 14. Most notably, <code>ObjectImpl</code> is not a mere typedef but inherits from hash map; the reason for this to avoid undefined behavior of parameterizing <code>std::unordered_map</code> with an incomplete type.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
struct dynamic::ObjectImpl : std::unordered_map&lt;dynamic, dynamic&gt; {};

// ...

inline dynamic::dynamic(ObjectMaker (*)())
  : type_(OBJECT)
{
  new (getAddress&lt;ObjectImpl&gt;()) ObjectImpl();
}

inline dynamic::dynamic(char const* s)
  : type_(STRING)
{
  new (&amp;u_.string) fbstring(s);
}

			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 14</td>
	</tr>
</table>

<p>The gist of the <code>folly</code>â€™s conversion facilities is shown in the Listing 15. The listing shows the code involved in conversion of <code>dynamic</code> to <code>fbstring</code>. The actual code of converting â€˜anything to anythingâ€™, as the documentation states, is in a separate header and too large for inclusion here. For binary/decimal and vice-versa conversion of IEEE doubles, the class uses V8 double-conversion [<a href="#[Double.Conversion]">Double.Conversion</a>].</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template&lt;&gt; struct dynamic::GetAddrImpl&lt;bool&gt; {
  static bool* get(Data&amp; d) {
    return &amp;d.boolean; }
};
template&lt;&gt; struct dynamic::GetAddrImpl&lt;int64_t&gt; {
  static int64_t* get(Data&amp; d) {
    return &amp;d.integer; }
};
template&lt;class T&gt;
T* dynamic::getAddress() {
  return GetAddrImpl&lt;T&gt;::get(u_);
}
template&lt;class T&gt;
T* dynamic::get_nothrow() {
  if (type_ != TypeInfo&lt;T&gt;::type) {
    return nullptr;
  }
  return getAddress&lt;T&gt;();
}
template&lt;class T&gt;
T dynamic::asImpl() const
{
  switch (type())
  {
    case INT64:
      return to&lt;T&gt;(*get_nothrow&lt;int64_t&gt;());
    case DOUBLE:
      return to&lt;T&gt;(*get_nothrow&lt;double&gt;());
    case BOOL:
      return to&lt;T&gt;(*get_nothrow&lt;bool&gt;());
    case STRING:
      return to&lt;T&gt;(*get_nothrow&lt;fbstring&gt;());
    default:
      throw TypeError(&quot;int/double/bool/string&quot;,
                      type());
  }
}
inline fbstring dynamic::asString() const
{
  return asImpl&lt;fbstring&gt;();
} 
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 15</td>
	</tr>
</table>

<p>As will be shown in one of the next installments, <code>dynamic</code> provides a very nice user interface, yet also provides a lot in terms of performance. It is a class designed with definite business goal in mind and it succeeds in that endeavor. The only downside for the whole <code>folly</code> library is a patchy build system which requires a significant effort to build the library. The library is also not portable, at least not in the out-of-the-box fashion.</p>

<h2>Conclusion</h2>

<p>In this installment, we reviewed three C++ dynamic typing solutions: <strong>Boost</strong> <code>type_erasure</code>, <strong>PicklingTools</strong> <code>Val</code> and <strong>Facebook</strong> <code>folly::dynamic</code>. While <code>dynamic</code> and <code>Val</code> provide dynamically-typed storage within the confines of the standard C++, <code>type_erasure</code> also ventures in a new direction by adding operations to C++ types. In the next installment, weâ€™ll look into more similar solutions, so stay tuned â€¦</p>

<h2>Credits</h2>

<p>Steven Watanabe provided valuable advice on <code>boost::type_erasure</code>. The list is, of course, not inclusive - many other people, discussions, libraries and code samples were an indispensable source of help in gathering and systematizing this writing. </p>

<h2>References and further information</h2>

<p class="bibliomixed"><a id="[Boost.Any]"></a>[Boost.Any]  <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/any.html">http://www.boost.org/doc/libs/1_53_0/doc/html/any.html</a></p>

<p class="bibliomixed"><a id="[Boost.Function]"></a>[Boost.Function]  <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/function.html">http://www.boost.org/doc/libs/1_53_0/doc/html/function.html</a></p>

<p class="bibliomixed"><a id="[Boost.TypeErasure]"></a>[Boost.TypeErasure]  <a href="http://www.boost.org/doc/libs/1_54_0/doc/html/boost_typeerasure.html">http://www.boost.org/doc/libs/1_54_0/doc/html/boost_typeerasure.html</a></p>

<p class="bibliomixed"><a id="[Double.Conversion]"></a>[Double.Conversion]  â€˜Double-conversion libraryâ€™ <a href="https://code.google.com/p/double-conversion/">https://code.google.com/p/double-conversion/</a></p>

<p class="bibliomixed"><a id="[Folly.Dynamic]"></a>[Folly.Dynamic]  Facebook folly library, dynamic class â€“ <a href="https://github.com/facebook/folly/blob/master/folly/docs/Dynamic.md">https://github.com/facebook/folly/blob/master/folly/docs/Dynamic.md</a></p>

<p class="bibliomixed"><a id="[GotW28]"></a>[GotW28]  The Fast Pimpl Idiom  <a href="http://www.gotw.ca/gotw/028.htm">http://www.gotw.ca/gotw/028.htm</a></p>

<p class="bibliomixed"><a id="[jemalloc]"></a>[jemalloc]  A general-purpose scalable concurrent malloc(3) implementation <a href="http://www.canonware.com/jemalloc/">http://www.canonware.com/jemalloc/</a></p>

<p class="bibliomixed"><a id="[PicklingTools]"></a>[PicklingTools]  The PicklingTools Library <a href="www.picklingtools.com">www.picklingtools.com</a></p>

<p class="bibliomixed"><a id="[Saunders1]"></a>[Saunders1]  â€˜Dynamic, Recursive, Heterogeneous Types in Statically-Typed Languagesâ€™, Clinton Jeffery, Richard Saunders, <em>C++ Now</em> 2013 Presentation, <a href="http://cppnow.org/session/dynamic-recursive-heterogeneous-types-in-statically-typed-languages/">http://cppnow.org/session/dynamic-recursive-heterogeneous-types-in-statically-typed-languages/</a></p>

<p class="bibliomixed"><a id="[Saunders2]"></a>[Saunders2]  â€˜Dynamic, Recursive, Heterogeneous Types in Statically-Typed Languagesâ€™ Clinton Jeffery, Richard Saunders <a href="http://cppnow.org/files/2013/03/saunders-jeffery.pdf">http://cppnow.org/files/2013/03/saunders-jeffery.pdf</a> </p>

<p class="bibliomixed"><a id="[Saunders3]"></a>[Saunders3]  <em>C++ Now 2013</em> Presentation, Richard Saunders <a href="http://www.youtube.com/watch?v=W3TsQtnMtqg">http://www.youtube.com/watch?v=W3TsQtnMtqg</a></p>

<p class="bibliomixed"><a id="[Venners04]"></a>[Venners04]  â€˜Abstraction and Efficiency: A Conversation with Bjarne Stroustrupâ€™ by Bill Venners, February 16, 2004 <a href="http://www.artima.com/intv/abstreffi.html">http://www.artima.com/intv/abstreffi.html</a></p>

<p class="bibliomixed"><a id="[Wikipedia]"></a>[Wikipedia]  Boyerâ€“Moore string search algorithm http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm</p>

<h3>Further information</h3>

<p class="bibliomixed">â€˜Dynamic C++â€™, ACCU 2013 Conference<a href="http://www.slideshare.net/aleks-f/dynamic-caccu2013">http://www.slideshare.net/aleks-f/dynamic-caccu2013</a></p>

<p class="bibliomixed">Facebook folly library, fbstring class â€“ <a href="https://github.com/facebook/folly/blob/master/folly/docs/FBString.md">https://github.com/facebook/folly/blob/master/folly/docs/FBString.md</a></p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
