<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.3.2: http://docutils.sourceforge.net/" />
<title>A Library Approach to Initialization</title>
<meta name="author" content="T(h)orsten Ottosen" />
<meta name="organization" content="Department of Computer Science, Aalborg University, and Dezide Aps" />
<meta name="date" content="29th of October 2004" />
<meta name="copyright" content="T(h)orsten Ottosen 2004. All rights reserved" />
<style type="text/css"><!--

/*
:Author: David Goodger
:Contact: goodger@users.sourceforge.net
:date: $Date: 2004/01/12 02:49:54 $
:version: $Revision: 1.2 $
:copyright: This stylesheet has been placed in the public domain.

Default cascading style sheet for the HTML output of Docutils.
*/

.first {
  margin-top: 0 }

.last {
  margin-bottom: 0 }

a.toc-backref {
  text-decoration: none ;
  color: black }

dd {
  margin-bottom: 0.5em }

div.abstract {
  margin: 2em 5em }

div.abstract p.topic-title {
  font-weight: bold ;
  text-align: center }

div.attention, div.caution, div.danger, div.error, div.hint,
div.important, div.note, div.tip, div.warning, div.admonition {
  margin: 2em ;
  border: medium outset ;
  padding: 1em }

div.attention p.admonition-title, div.caution p.admonition-title,
div.danger p.admonition-title, div.error p.admonition-title,
div.warning p.admonition-title {
  color: red ;
  font-weight: bold ;
  font-family: sans-serif }

div.hint p.admonition-title, div.important p.admonition-title,
div.note p.admonition-title, div.tip p.admonition-title,
div.admonition p.admonition-title {
  font-weight: bold ;
  font-family: sans-serif }

div.dedication {
  margin: 2em 5em ;
  text-align: center ;
  font-style: italic }

div.dedication p.topic-title {
  font-weight: bold ;
  font-style: normal }

div.figure {
  margin-left: 2em }

div.footer, div.header {
  font-size: smaller }

div.sidebar {
  margin-left: 1em ;
  border: medium outset ;
  padding: 0em 1em ;
  background-color: #ffffee ;
  width: 40% ;
  float: right ;
  clear: right }

div.sidebar p.rubric {
  font-family: sans-serif ;
  font-size: medium }

div.system-messages {
  margin: 5em }

div.system-messages h1 {
  color: red }

div.system-message {
  border: medium outset ;
  padding: 1em }

div.system-message p.system-message-title {
  color: red ;
  font-weight: bold }

div.topic {
  margin: 2em }

h1.title {
  text-align: center }

h2.subtitle {
  text-align: center }

hr {
  width: 75% }

ol.simple, ul.simple {
  margin-bottom: 1em }

ol.arabic {
  list-style: decimal }

ol.loweralpha {
  list-style: lower-alpha }

ol.upperalpha {
  list-style: upper-alpha }

ol.lowerroman {
  list-style: lower-roman }

ol.upperroman {
  list-style: upper-roman }

p.attribution {
  text-align: right ;
  margin-left: 50% }

p.caption {
  font-style: italic }

p.credits {
  font-style: italic ;
  font-size: smaller }

p.label {
  white-space: nowrap }

p.rubric {
  font-weight: bold ;
  font-size: larger ;
  color: maroon ;
  text-align: center }

p.sidebar-title {
  font-family: sans-serif ;
  font-weight: bold ;
  font-size: larger }

p.sidebar-subtitle {
  font-family: sans-serif ;
  font-weight: bold }

p.topic-title {
  font-weight: bold }

pre.address {
  margin-bottom: 0 ;
  margin-top: 0 ;
  font-family: serif ;
  font-size: 100% }

pre.line-block {
  font-family: serif ;
  font-size: 100% }

pre.literal-block, pre.doctest-block {
  margin-left: 2em ;
  margin-right: 2em ;
  background-color: #eeeeee }

span.classifier {
  font-family: sans-serif ;
  font-style: oblique }

span.classifier-delimiter {
  font-family: sans-serif ;
  font-weight: bold }

span.interpreted {
  font-family: sans-serif }

span.option {
  white-space: nowrap }

span.option-argument {
  font-style: italic }

span.pre {
  white-space: pre }

span.problematic {
  color: red }

table {
  margin-top: 0.5em ;
  margin-bottom: 0.5em }

table.citation {
  border-left: solid thin gray ;
  padding-left: 0.5ex }

table.docinfo {
  margin: 2em 4em }

table.footnote {
  border-left: solid thin black ;
  padding-left: 0.5ex }

td, th {
  padding-left: 0.5em ;
  padding-right: 0.5em ;
  vertical-align: top }

th.docinfo-name, th.field-name {
  font-weight: bold ;
  text-align: left ;
  white-space: nowrap }

h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt {
  font-size: 100% }

tt {
  background-color: #eeeeee }

ul.auto-toc {
  list-style-type: none }
  
pre{
  BORDER-RIGHT: gray 1pt solid;
  PADDING-RIGHT: 2pt;
  BORDER-TOP: gray 1pt solid;
  DISPLAY: block;
  PADDING-LEFT: 2pt;
  PADDING-BOTTOM: 2pt;
  BORDER-LEFT: gray 1pt solid;
  MARGIN-RIGHT: 32pt;
  PADDING-TOP: 2pt;
  BORDER-BOTTOM: gray 1pt solid;
  FONT-FAMILY: "Courier New", Courier, mono; 
  background-color: #EEEEEE; 
}


.keyword{color: #0000FF;}
.identifier{}
.comment{font-style: italic; color: #008000;}
.special{color: #800040;}
.preprocessor{color: #3F007F;}
.string{font-style: italic; color: #666666;}
.literal{/*font-style: italic;*/ color: #000000;}

--></style>
</head>
<body>
<h1 class="title">A Library Approach to Initialization</h1>
<table class="docinfo" frame="void" rules="none">
<col class="docinfo-name" />
<col class="docinfo-content" />
<tbody valign="top">
<tr><th class="docinfo-name">Author:</th>
<td>T(h)orsten Ottosen</td></tr>
<tr><th class="docinfo-name">Contact:</th>
<td><a class="first last reference" href="mailto:nesotto&#64;cs.auc.dk">nesotto&#64;cs.auc.dk</a></td></tr>
<tr><th class="docinfo-name">Organization:</th>
<td><a class="first reference" href="http://www.cs.auc.dk">Department of Computer Science</a>, Aalborg University, and <a class="last reference" href="http://www.dezide.com">Dezide Aps</a></td></tr>
<tr><th class="docinfo-name">Date:</th>
<td>29th of October 2004</td></tr>
<tr class="field"><th class="docinfo-name">Number:</th><td class="field-body">WG21/N1724 and J16/04-0164.</td>
</tr>
<tr class="field"><th class="docinfo-name">Working Group:</th><td class="field-body">Evolution</td>
</tr>
<tr><th class="docinfo-name">Copyright:</th>
<td>T(h)orsten Ottosen 2004. All rights reserved</td></tr>
</tbody>
</table>
<div class="document" id="a-library-approach-to-initialization">
<!-- :Abstract: This paper explains the pros and cons of a library approach
to initialization.  -->
<div class="contents topic" id="table-of-contents">
<p class="topic-title"><a name="table-of-contents">Table of Contents</a></p>
<ul class="auto-toc simple">
<li><a class="reference" href="#introduction" id="id4" name="id4">1   Introduction</a></li>
<li><a class="reference" href="#the-current-solution" id="id5" name="id5">2   The current solution</a></li>
<li><a class="reference" href="#advanced-usage" id="id6" name="id6">3   Advanced usage</a></li>
<li><a class="reference" href="#conclusion" id="id7" name="id7">4   Conclusion</a></li>
</ul>
</div>
<div class="section" id="introduction">
<h1><a class="toc-backref" href="#id4" name="introduction">1   Introduction</a></h1>
<p>The standard committee is actively pursuing ways to enhance the initialization 
syntax of the language so eg. standard containers can use the same syntax as
we currently use for built-in arrays.
This paper briefly explains what we can currently do without any changes to the 
core language. The solution shown in this document is based on the authors
experience from implementing boost.assign, a new library in version 1.32.0 of <a class="reference" href="http://www.boost.org">boost</a></p>
</div>
<div class="section" id="the-current-solution">
<h1><a class="toc-backref" href="#id5" name="the-current-solution">2   The current solution</a></h1>
<p>Consider the following UDT:</p>
<pre class="literal-block">
struct Foo
{
    Foo();               // #1
    Foo( int );          // #2
    Foo( string );       // #3
    Foo( int, string );  // #4
};
</pre>
<p>Then we can make an array of <tt class="literal"><span class="pre">Foo</span></tt> as follows:</p>
<pre class="literal-block">
tr1::array&lt;Foo,42&gt; = list_of&lt;Foo&gt;( 5 )( &quot;foo&quot; )( 42, &quot;bar&quot; )();
</pre>
<p>This works by</p>
<ol class="arabic simple">
<li>creating a temporary container</li>
<li>constructing <tt class="literal"><span class="pre">Foo</span></tt> objects by passing the provided arguments to the constructor</li>
<li>adding the elements to the temporary container</li>
<li>converting the temporary container to <tt class="literal"><span class="pre">tr1::array&lt;Foo,42&gt;</span></tt> via a generic conversion operator.</li>
</ol>
<p>Note that</p>
<ul class="simple">
<li>we call all constructors in the order (#2,#3,#4,#1).</li>
<li>the conversion is run-time bounds-checked if more than 42 elements are provided</li>
<li>missing elements are default-constructed</li>
<li>the same syntax would work for all standard sequence containers (and more)</li>
<li>the code is fairly inefficient; boost.assign provides alternative syntaxes 
that are efficient, but which cannot be used for direct initialization</li>
</ul>
<p>Efficiency is probably not a concern in this context.</p>
<p>For maps we can do something similar:</p>
<pre class="literal-block">
std::map&lt;string,int&gt; m = 
    map_list_of ( &quot;january&quot;,   31 )( &quot;february&quot;, 28 )
                ( &quot;march&quot;,     31 )( &quot;april&quot;,    30 )
                ( &quot;may&quot;,       31 )( &quot;june&quot;,     30 )
                ( &quot;july&quot;,      31 )( &quot;august&quot;,   31 )
                ( &quot;september&quot;, 30 )( &quot;october&quot;,  31 )
                ( &quot;november&quot;,  30 )( &quot;december&quot;, 31 );
</pre>
<p>where <tt class="literal"><span class="pre">map_list_of()</span></tt> is simply a short-hand for <tt class="literal"><span class="pre">list_of&lt;std::pair&lt;T1,T2&gt;&gt;()</span></tt>.</p>
<p>Users quickly wanted to insert hooks into the sequence used for initialization;
for example, few people want to write the same constant <cite>N</cite> times:</p>
<pre class="literal-block">
const std::vector&lt;int&gt; v = list_of&lt;int&gt;( 1 )( 2 ).repeat_fun( 10, &amp;std::rand )( 4 )( 5 ).repeat( 10, 6 );
</pre>
<p>Here <tt class="literal"><span class="pre">repeat_fun()</span></tt> inserts 10 random numbers whereas <tt class="literal"><span class="pre">repeat()</span></tt> inserts 10 instances
of 6. Such flexibility is a major benefit of a library approach.</p>
<p>More complicated examples can also be constructed:</p>
<pre class="literal-block">
typedef vector&lt;int&gt;                   score_type;
typedef map&lt;string,score_type&gt;        team_score_map;
typedef pair&lt;string,score_type&gt;       score_pair;

team_score_map group = list_of&lt; score_pair &gt;
                             ( &quot;Norway&quot;,  list_of(1)(0)(0) )
                             ( &quot;USA&quot;,     list_of(0)(0)(0) )
                             ( &quot;Andorra&quot;, list_of(0)(1)(1) );
 BOOST_ASSERT( group.size() == 3 );
 BOOST_ASSERT( group[ &quot;Norway&quot; ][0] == 1 );
 BOOST_ASSERT( group[ &quot;USA&quot; ][0] == 0 );
</pre>
<p>A more thorough tutorial can be found in the documentation of <a class="reference" href="http://www.boost.org/libs/assign/">boost.assign</a>
(when version 1.32.0 of boost is released).</p>
</div>
<div class="section" id="advanced-usage">
<h1><a class="toc-backref" href="#id6" name="advanced-usage">3   Advanced usage</a></h1>
<p>The function <tt class="literal"><span class="pre">list_of()</span></tt> and its siblings can also be used to create
anonymous sequences. With a little more hacking we can make some quite
useful and efficient abstractions possible.</p>
<p>Assume we have the following helper function:</p>
<pre class="literal-block">
template&lt; class Range &gt;
void print( const Range&amp; r )
{
   std::cout &lt;&lt; &quot;\n&quot;;
   for( typename Range::const_iterator i = r.begin(), e = r.end();
        i !=e; ++i )
        std::cout &lt;&lt; &quot; &quot; &lt;&lt; *i;
}
</pre>
<p>An efficient way to create an anonymous sequence is possible if we ask the 
programmer to specify the length of the sequence:</p>
<pre class="literal-block">
int a=1,b=5,c=3,d=4,e=2,f=9,g=0,h=7;
print( list_of&lt;8&gt;(a)(b)(c)(d)(e)(f)(g)(h) );
</pre>
<p>The fact that we must specify the length to get an efficient solution is
somewhat irritating.</p>
<p>Another interesting possibility of the library solution is that we can 
make sequences of references---a language solution can probably not do this.  
For example, this is possible by using some simple reference wrapper 
class:</p>
<pre class="literal-block">
template&lt; class Range &gt;
typename Range::const_iterator max_element( const Range&amp; r )
{
    return std::max_element( r.begin(), r.end() );
}
        
int&amp; max = *max_element( list_of&lt;8,int&amp;&gt;(a)(b)(c)(d)(e)(f)(g)(h) );
</pre>
<p>In some cases we might be able to call mutating algorithms too; calling 
eg.  <tt class="literal"><span class="pre">std::sort()</span></tt> will require a standard library that guarantees to 
perform all swaps with a user-defined <tt class="literal"><span class="pre">swap()</span></tt> (if it exists).  The 
standard library currently does not give such guarantees; however, it is 
the author's opinion that such a guarantee would be useful in several other 
situations.</p>
</div>
<div class="section" id="conclusion">
<h1><a class="toc-backref" href="#id7" name="conclusion">4   Conclusion</a></h1>
<p>The benefits of a library solution are</p>
<ul class="simple">
<li>no change to the core language needed</li>
<li>flexible call-backs can insert elements in the sequences</li>
<li>sequences of references can be constructed</li>
</ul>
<p>The problems with a library solution are</p>
<ul class="simple">
<li>the length of the sequences cannot be deduced at compile time;
this leads to either a more clumsy usage or to inefficiencies.</li>
<li>the type of the conversion cannot be determined early enough for 
an efficient conversion <a class="footnote-reference" href="#id3" id="id2" name="id2"><sup>1</sup></a></li>
<li>we cannot emulate the normal initialization syntax of the language</li>
</ul>
<!-- ############################################### -->
<!-- ################## Links ###################### -->
<!-- ############################################### -->
<!-- ############################################### -->
<!-- ################## Footnotes ################## -->
<!-- ############################################### -->
<table class="footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2" name="id3">[1]</a></td><td>Would anyone dare to suggest overloading on return types? :-)</td></tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
