<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>The Lazy Programmer</title>
	<atom:link href="https://tlzprgmr.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://tlzprgmr.wordpress.com</link>
	<description>A few things I&#039;ve been working on</description>
	<lastBuildDate>Wed, 09 Jun 2010 14:21:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='tlzprgmr.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>https://secure.gravatar.com/blavatar/ac1cea40891d1134fb2acec5e308a352?s=96&#038;d=https%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>The Lazy Programmer</title>
		<link>https://tlzprgmr.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="https://tlzprgmr.wordpress.com/osd.xml" title="The Lazy Programmer" />
	<atom:link rel='hub' href='https://tlzprgmr.wordpress.com/?pushpress=hub'/>
	<item>
		<title>An XML Writer for C++</title>
		<link>https://tlzprgmr.wordpress.com/2010/06/07/an-xml-writer-for-c/</link>
		<pubDate>Mon, 07 Jun 2010 14:31:15 +0000</pubDate>
		<dc:creator><![CDATA[ferruccio]]></dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[XML]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[xml-writer]]></category>

		<guid isPermaLink="false">http://tlzprgmr.wordpress.com/2010/06/07/an-xml-writer-for-c/</guid>
		<description><![CDATA[I’ve worked on a couple of projects where XML files were generated via printfs or iostreams and this has always turned out to be a mistake. Maintaining such code can be tricky and you always spend an inordinate amount of time debugging the same type of problems over and over again. Usually a character with [&#8230;]<img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=174&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I’ve worked on a couple of projects where XML files were generated via printfs or iostreams and this has always turned out to be a mistake. Maintaining such code can be tricky and you always spend an inordinate amount of time debugging the same type of problems over and over again. Usually a character with special meaning to XML (such as &lt; or &gt;) winds up not getting quoted correctly or you forget an end element tag.</p>
<p>The project I’m currently working on involves a search engine which returns its results in XML over an HTTP connection. I decided to use an XML writer rather than make the same mistake again. After looking around for an open source solution and not finding anything suitable for my needs, I decided to roll my own and place the project on <a href="http://code.google.com/p/xml-writer-cpp/">Google Code</a>.</p>
<p>To use xml-writer, simply drop xml_writer.h into your project directory and #include it as necessary. It is a very simple (less than 200 LOC) class. The accompanying unit tests also serve as documentation for its use.</p>
<p>Briefly, you instantiate an xml::writer object bound to an std::ostream. This allows you to send the resulting XML to a string (std::stringstream), a file (std::fostream) or any ostream compatible object. In my case, I created a stream object which writes directly to an HTTP connection.</p>
<p>You instantiate xml::element objects to actually create the XML element tags. An xml::element object has overloaded attr() methods to write element attributes and contents() to write element contents. When an xml::element object goes out of scope, it will write the necessary end element tag.</p>
<p>A simple example:</p>
<pre><font size="+1">#include "xml_writer.h"
#include &lt;sstream&gt;
#include &lt;iostream&gt;

using namespace std;

int main()
{
    stringstream ss;
    xml::writer xw(ss);
    {
        xml::element record("record", xw);
        record.attr("name", "fred").attr("age", 35);
        record.contents("yabba dabba doo!");
    }
    cout &lt;&lt; ss.str() &lt;&lt; endl;
    return 0;
}</font></pre>
<p>will result in the following output:</p>
<p><span style="font-family:'Courier New';">&lt;?xml version=&#8221;1.0&#8243; encoding=&#8221;utf-8&#8243;?&gt;&lt;record name=&#8221;fred&#8221; age=&#8221;35&#8243;&gt;yabba dabba doo!&lt;/record&gt;</span></p>
<p>NB: the extra scope created to encapsulate the record element was necessary so that the xml::element destructor is called before the resulting string is output. xml::element should always be enclosed in some kind of local scope for this to work properly.</p><br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tlzprgmr.wordpress.com/174/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tlzprgmr.wordpress.com/174/" /></a> <img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=174&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
		
		<media:content url="http://2.gravatar.com/avatar/e4a1b4bf6865eddd0edfe8cb90361c84?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">ferruccio</media:title>
		</media:content>
	</item>
		<item>
		<title>.NET DeflateStream/zlib compatibility</title>
		<link>https://tlzprgmr.wordpress.com/2010/03/17/net-deflatestreamzlib-compatibility/</link>
		<pubDate>Wed, 17 Mar 2010 20:37:14 +0000</pubDate>
		<dc:creator><![CDATA[ferruccio]]></dc:creator>
				<category><![CDATA[/NET]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://tlzprgmr.wordpress.com/?p=163</guid>
		<description><![CDATA[This is just a quick post to describe how to format compressed data with the .NET DeflateStream class so that it can be read back in a C or C++ program using zlib. Compressing data with DeflateStream is extremely simple. The original code I was using looked like this: using (var compressor = new DeflateStream(data, [&#8230;]<img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=163&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>This is just a quick post to describe how to format compressed data with the .NET DeflateStream class so that it can be read back in a C or C++ program using zlib. Compressing data with DeflateStream is extremely simple. The original code I was using looked like this:<span id="more-163"></span></p>
<p><code> </code></p>
<pre>using (var compressor = new DeflateStream(data, CompressionMode.Compress))
    compressor.Write(bytes, 0, bytes.Length);</pre>
<p>data is a MemoryStream that I used to serialize the compressed data to disk.</p>
<p>zlib refused to read it. It kept throwing a &#8220;zlib error&#8221; exception.</p>
<p>It turns out that although they use the same compression algorithm, zlib expects a header in front of the data and an adler-32 checksum at the end. The code is now:</p>
<p><code> </code></p>
<pre>data.WriteByte(0x58);
data.WriteByte(0x85);
using (var compressor = new DeflateStream(data, CompressionMode.Compress, true))
    compressor.Write(bytes, 0, bytes.Length);
data.Write(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(Adler32(bytes))), 0, sizeof(uint));</pre>
<p>the adler-32 code:<br />
<code> </code></p>
<pre>// naive implementation of adler-32 checksum
int Adler32(byte[] bytes) {
    const uint a32mod = 65521;
    uint s1 = 1, s2 = 0;
    foreach (byte b in bytes) {
        s1 = (s1 + b) % a32mod;
        s2 = (s2 + s1) % a32mod;
    }
    return unchecked((int) ((s2 &lt;&lt; 16) + s1));
}</pre>
<p>and zlib is happy again.</p>
<p>If you&#8217;re wondering what the magic numbers are, take a look at <a href="http://www.rfc-archive.org/getrfc.php?rfc=1950">RFC 1950</a>.</p><br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tlzprgmr.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tlzprgmr.wordpress.com/163/" /></a> <img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=163&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
		
		<media:content url="http://2.gravatar.com/avatar/e4a1b4bf6865eddd0edfe8cb90361c84?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">ferruccio</media:title>
		</media:content>
	</item>
		<item>
		<title>Building Boost 1.42 with zlib 1.2.4 support</title>
		<link>https://tlzprgmr.wordpress.com/2010/03/17/building-boost-1-42-with-zlib-1-2-4-support/</link>
		<comments>https://tlzprgmr.wordpress.com/2010/03/17/building-boost-1-42-with-zlib-1-2-4-support/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 12:09:08 +0000</pubDate>
		<dc:creator><![CDATA[ferruccio]]></dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[c++ boost zlib]]></category>

		<guid isPermaLink="false">http://tlzprgmr.wordpress.com/?p=148</guid>
		<description><![CDATA[I am currently using Boost.IOStreams to read some compressed data out of a database. When I tried to user a zlib_decompressor object to deflate the incoming stream, it failed to compile. It turns out that you have to add zlib to the boost build process,  so I grabbed a copy of the latest zlib sources [&#8230;]<img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=148&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I am currently using Boost.IOStreams to read some compressed data out of a database. When I tried to user a zlib_decompressor object to deflate the incoming stream, it failed to compile. It turns out that you have to add zlib to the boost build process,  so I grabbed a copy of the latest zlib sources and made the necessary change to my boost build script (added -sZLIB_SOURCE=&#8230; so that boost.build could find the zlib sources).</p>
<p>Unfortunately the build failed. Bjam complained that it was missing a dependency (gzio.c). After a bit of trial and error with various boost.build options, I found the problem. I checked the <a href="http://www.zlib.net/ChangeLog.txt">zlib change</a> log and it turns out that in version 1.2.3.9 they removed the gzio.c file from the zlib sources.  Unfortunately, this was a very recent change so boost.build has not yet been updated to reflect the current zlib.<span id="more-148"></span></p>
<p>The fix is simple. Look in the boost source tree in the /libs/iostreams/build directory. There is a file named Jamfile.v2. Remove the gzio reference from line 136 so that it reads:</p>
<pre>crc32 deflate infback inffast inflate inftrees trees uncompr zutil :</pre>
<p>That&#8217;s all you need to do. Boost should now build and incorporate zlib into boost.iostreams. I added a command to my boost build script to automatically make this change. It uses the Gnuwin32 sed command:</p>
<pre>sed -i s/gzio//g "%BOOST_ROOT%\libs\iostreams\build\jamfile.v2"
</pre>
<p>Here is my complete build script. It builds Boost for Win32 using statically linked boost libraries and C runtime. It assumes that you have boost_1_42_0.zip and zlib124.zip in the same directory as the build script. It also assumes that you have bjam.exe and the following Gnuwin32 tools in your path: unzip.exe, sed.exe, and grep.exe.</p>
<pre><code>setlocal

set BOOST_MAJOR=1
set BOOST_MINOR=42
set BOOST_REV=0

set ZLIB_MAJOR=1
set ZLIB_MINOR=2
set ZLIB_REV=4

set INSTALL=c:\boost

set VC_ROOT=%PROGRAMFILES%\Microsoft Visual Studio 9.0\VC
set TOOLSET=msvc-9.0
set ZLIB_ROOT=%CD%\zlib-%ZLIB_MAJOR%.%ZLIB_MINOR%.%ZLIB_REV%

set PARAM=--without-mpi toolset=%TOOLSET%
set PARAM=%PARAM% -sZLIB_SOURCE="%ZLIB_ROOT%"

set BOOST_ROOT=%CD%\boost_%BOOST_MAJOR%_%BOOST_MINOR%_%BOOST_REV%
set BUILD=%CD%\build
set STAGE=%CD%\stage

path %CD%;%PATH%

if exist "%STAGE%-x86\lib" del /q "%STAGE%-x86\lib\*"

if not exist "%ZLIB_ROOT%" unzip zlib*.zip
if not exist "%BOOST_ROOT%" unzip boost*.zip

sed -i s/gzio//g "%BOOST_ROOT%\libs\iostreams\build\jamfile.v2"

pushd "%BOOST_ROOT%"
setlocal
call "%VC_ROOT%\vcvarsall.bat" x86

set PARAM=%PARAM% variant=debug variant=release link=static runtime-link=static threading=multi
bjam %PARAM% --build-dir="%BUILD%-x86" --stagedir="%STAGE%-x86" stage

cd "%STAGE%-x86\lib"
dir /b | grep -v "\-%BOOST_MAJOR%_%BOOST_MINOR%" | sed "s/^/del /" | cmd

if exist "%INSTALL%" rd /s /q "%INSTALL%"
xcopy /s /i "%STAGE%-x86\lib" "%INSTALL%\lib-x86"
xcopy /s /i "%BOOST_ROOT%\boost" "%INSTALL%\include\boost-%BOOST_MAJOR%_%BOOST_MINOR%\boost"

endlocal
popd

endlocal
</code></pre><br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tlzprgmr.wordpress.com/148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tlzprgmr.wordpress.com/148/" /></a> <img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=148&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://tlzprgmr.wordpress.com/2010/03/17/building-boost-1-42-with-zlib-1-2-4-support/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e4a1b4bf6865eddd0edfe8cb90361c84?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">ferruccio</media:title>
		</media:content>
	</item>
		<item>
		<title>Berkeley DB Viewer</title>
		<link>https://tlzprgmr.wordpress.com/2010/03/02/berkeley-db-viewer/</link>
		<comments>https://tlzprgmr.wordpress.com/2010/03/02/berkeley-db-viewer/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 16:27:33 +0000</pubDate>
		<dc:creator><![CDATA[ferruccio]]></dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[berkeley-db]]></category>
		<category><![CDATA[viewer]]></category>

		<guid isPermaLink="false">http://tlzprgmr.wordpress.com/?p=130</guid>
		<description><![CDATA[I&#8217;m currently working on a project which uses Berkeley DB (BDB) as it&#8217;s data storage engine. I can&#8217;t say enough good things about BDB. It has proven to be a very fast and flexible way to store and retrieve data, it is very easy to use and the documentation is absolutely top notch. One issue [&#8230;]<img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=130&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I&#8217;m currently working on a project which uses Berkeley DB (BDB) as it&#8217;s data storage engine. I can&#8217;t say enough good things about BDB. It has proven to be a very fast and flexible way to store and retrieve data, it is very easy to use and the documentation is absolutely top notch.</p>
<p>One issue I ran into, though, is that there is no good way to examine the databases for debugging purposes. Initially, I used the provided db_dump command-line tool, which was fine for small databases. Db_dump dumps the entire contents of a database, which was OK when I was dealing with databases with only a few records. But now I am working with databases with thousands and soon millions of records. Db_dump just won&#8217;t do.<span id="more-130"></span></p>
<p>I did a bit of googling but there didn&#8217;t seem to be any viewers available for Berkeley DB, so I decided to write one. I was going to do it in C# and WPF because that&#8217;s what I&#8217;m currently using. But I decided that, since BDB is cross-platform, a viewer for it should also be cross-platform. So I decided to use Qt to build the viewer.</p>
<p>After a couple of nights of coding, here is the result:</p>
<p><img src="https://tlzprgmr.files.wordpress.com/2010/03/bdbvu.png" alt="bdbvu" /></p>
<p>The interface is pretty simple. There is a button for opening a BDB database file. Once a database is opened, the &#8220;Database&#8221; combo-box let&#8217;s you pick which sub-database to view (in BDB terms a database is a key/value table and a single file can contain multiple &#8220;databases&#8221;). The list view on the left shows all the keys in that database and the view on the right shows the contents at that key. Both keys and values are formatted the same as db_dump -p -k formats them.</p>
<p>I put the source code for Berkeley DB Viewer (bdbvu) on Google Code. You can grab it at: <a href="http://code.google.com/p/bdbvu/">http://code.google.com/p/bdbvu/</a>.</p>
<p>To build it you need two things:</p>
<ol>
<li> <a href="http://www.oracle.com/technology/software/products/berkeley-db/index.html">Berkeley DB</a>, installed and built with C++ support.</li>
<li> <a href="http://qt.nokia.com/downloads">Qt4</a>.</li>
</ol>
<p>Once you have those set up and you&#8217;ve downloaded the code, you will probably need to change the Qt project file to reflect your environment. I may enventually provide binary downloads, but I don&#8217;t have the time for that right now.</p>
<p>Finally, a few things to keep in mind:</p>
<ul>
<li>I&#8217;ve only tested this with DB_RECNO and DB_BTREE databases, since that&#8217;s what I&#8217;m using at this time. But, there&#8217;s no reason it shouldn&#8217;t work with DB_HASH and DB_QUEUE databases as well. (Where have I heard that before?)</li>
<li>I&#8217;ve only tested it with databases with embedded databases, not with stand-alone databases. I know it won&#8217;t work with stand-alone databases because the code for that is a no-op.</li>
<li>I&#8217;ve only built and run this on OS X. Theoretically, it should work on Windows and Linux as well, but you never know until you try it.</li>
<li>When you open a database, it will load all it&#8217;s keys into memory. This seems to be pretty quick (a couple of seconds for a 3000+ record database on my laptop) but I may have to change it to use a more scalable method in the future.</li>
</ul>
<p>That&#8217;s it for now. I hope you find this useful.</p><br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tlzprgmr.wordpress.com/130/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tlzprgmr.wordpress.com/130/" /></a> <img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=130&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://tlzprgmr.wordpress.com/2010/03/02/berkeley-db-viewer/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e4a1b4bf6865eddd0edfe8cb90361c84?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">ferruccio</media:title>
		</media:content>

		<media:content url="http://tlzprgmr.files.wordpress.com/2010/03/bdbvu.png" medium="image">
			<media:title type="html">bdbvu</media:title>
		</media:content>
	</item>
		<item>
		<title>OpenDiff/SVN command line shortcut</title>
		<link>https://tlzprgmr.wordpress.com/2009/09/19/opendiffsvn-command-line-shortcut/</link>
		<comments>https://tlzprgmr.wordpress.com/2009/09/19/opendiffsvn-command-line-shortcut/#comments</comments>
		<pubDate>Sat, 19 Sep 2009 13:18:02 +0000</pubDate>
		<dc:creator><![CDATA[ferruccio]]></dc:creator>
				<category><![CDATA[OSX]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[SVN]]></category>

		<guid isPermaLink="false">http://the-lazy-programmer.com/blog/?p=92</guid>
		<description><![CDATA[For cross-platform projects, I switched from using XCode to TextMate and CMake. I found this to be a more productive environment for me but I miss the OpenDiff integration that&#8217;s built into XCode. Most of the time svn diff is all I need, but for more complex changes the visualization provided by OpenDiff makes life [&#8230;]<img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=92&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>For cross-platform projects, I switched from using XCode to TextMate and CMake. I found this to be a more productive environment for me but I miss the OpenDiff integration that&#8217;s built into XCode. Most of the time <span style="font-family:monospace;">svn diff</span> is all I need, but for more complex changes the visualization provided by OpenDiff makes life so much easier.<span id="more-92"></span></p>
<p>It turns out that Subversion keeps a copy of the unedited version of your source code in its <span style="font-family:monospace;">.svn</span> directory. That was all I needed to build a command line shortcut to OpenDiff. The original source is kept in <span style="font-family:monospace;">.svn/text-base</span> and has a suffix of .svn-base. My first attempt was to create an alias:</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-family:monospace;"> $ alias od=&#8217;opendiff $1 .svn/text-base/$1.svn-base&#8217;</span></p>
<p>But, it turns out that bash aliases do not support parameter substitution. Who knew?</p>
<p>After a little more digging, I discovered you can define functions in bash. So the shortcut then became:</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-family:monospace;"> $ function od { opendiff $1 .svn/text-base/$1.svn-base; }</span></p>
<p>This did the trick. I can now start OpenDiff with a command like:</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-family:monospace;"> $ od source.cpp</span></p>
<p>Put the function definition in your <span style="font-family:monospace;">.profile</span> (or in <span style="font-family:monospace;">.bashrc</span> or in any of the many places you can put startup commands).</p><br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tlzprgmr.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tlzprgmr.wordpress.com/92/" /></a> <img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=92&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://tlzprgmr.wordpress.com/2009/09/19/opendiffsvn-command-line-shortcut/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e4a1b4bf6865eddd0edfe8cb90361c84?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">ferruccio</media:title>
		</media:content>
	</item>
		<item>
		<title>Dynamic C++ Update</title>
		<link>https://tlzprgmr.wordpress.com/2009/08/09/dynamic-c-update/</link>
		<pubDate>Sun, 09 Aug 2009 19:51:04 +0000</pubDate>
		<dc:creator><![CDATA[ferruccio]]></dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Dynamic-Typing]]></category>

		<guid isPermaLink="false">http://the-lazy-programmer.com/blog/?p=82</guid>
		<description><![CDATA[I&#8217;ve been tinkering with my Dynamic C++ project on occasion in order to get it to build successfully under OSX without much luck. Most of it built just fine, but there were a bunch of places where the boost::variant::apply_visitor() function was giving me all sorts of grief. The original problem was that I was passing [&#8230;]<img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=82&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been tinkering with my Dynamic C++ project on occasion in order to get it to build successfully under OSX without much luck. Most of it built just fine, but there were a bunch of places where the boost::variant::apply_visitor() function was giving me all sorts of grief.<br />
The original problem was that I was passing an instance of a locally defined struct as the functor argument to apply_visitor(), such as:</p>
<div>
<pre class="csharpcode">unsigned <span class="kwrd">int</span> var::count() <span class="kwrd">const</span> {
    <span class="kwrd">struct</span> count_visitor : <span class="kwrd">public</span> boost::static_visitor&lt;unsigned <span class="kwrd">int</span>&gt; {
        unsigned <span class="kwrd">int</span> <span class="kwrd">operator</span> () (null_t) <span class="kwrd">const</span> { <span class="kwrd">throw</span> exception(<span class="str">"invalid .count() operation on $"</span>); }
        unsigned <span class="kwrd">int</span> <span class="kwrd">operator</span> () (int_t) <span class="kwrd">const</span> { <span class="kwrd">throw</span> exception(<span class="str">"invalid .count() operation on int"</span>); }
        unsigned <span class="kwrd">int</span> <span class="kwrd">operator</span> () (double_t) <span class="kwrd">const</span> { <span class="kwrd">throw</span> exception(<span class="str">"invalid .count() operation on double"</span>); }
        unsigned <span class="kwrd">int</span> <span class="kwrd">operator</span> () (string_t s) <span class="kwrd">const</span> { <span class="kwrd">return</span> s.ps-&gt;length(); }
        unsigned <span class="kwrd">int</span> <span class="kwrd">operator</span> () (list_ptr l) <span class="kwrd">const</span> { <span class="kwrd">return</span> l-&gt;size(); }
        unsigned <span class="kwrd">int</span> <span class="kwrd">operator</span> () (array_ptr a) <span class="kwrd">const</span> { <span class="kwrd">return</span> a-&gt;size(); }
        unsigned <span class="kwrd">int</span> <span class="kwrd">operator</span> () (set_ptr s) <span class="kwrd">const</span> { <span class="kwrd">return</span> s-&gt;size(); }
        unsigned <span class="kwrd">int</span> <span class="kwrd">operator</span> () (dict_ptr d) <span class="kwrd">const</span> { <span class="kwrd">return</span> d-&gt;size(); }
    };

    <span class="kwrd">return</span> boost::apply_visitor(count_visitor(), _var);
}</pre>
</div>
<p><span id="more-82"></span></p>
<p>This worked fine with Visual C++ 9 but g++ did not like it one bit.  After a bit of research, I discovered that g++ was right and VC++ was letting me get away with non-standard C++. You can declare a struct inside a function, of course, but it cannot have access to any objects in the function scope. Since this was a member function of the var class, it could not have access to the internals of the var class.</p>
<p>No problem, I thought. I&#8217;ll just move all these structs into the global scope right before the functions that used them. Except that I had forgotten that all these structs needed access to the internals of the var class, which they had when declared inside a member function. Once outside the member function, the functor code suddenly broke. So, I moved all these structs right into the var class (destroying the locality of reference which I had been so careful to maintain).</p>
<p>Now it compiled fine with VC++, but g++ still gave me a few type errors. Again these all seemed to be caused  by apply_visitor(),  so I decided to drop most of the apply_visitor() calls in favor of switch statements. This would eliminate the few remaining errors but would, much more importantly, put the relevant code close to where it was actually being used.</p>
<p>The main benefit of using apply_visitor() is that if you forget to handle a type, it will generate a compile-time error. I used switch statements whose default block throws an exception. I traded compile-time checking with run-time checking. I can live with that.</p>
<p>Luckily, I had plenty of unit tests in place. I tend to work in increments. Make all necessary changes to a function, compile and test. Repeat until done. There were quite a few times when my changes compiled but failed when I ran the unit test suite. Once I decided to make these changes, it took a couple of hours to make them all and test the results. Everything builds cleanly in Visual Studio and XCode now.</p><br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tlzprgmr.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tlzprgmr.wordpress.com/82/" /></a> <img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=82&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
		
		<media:content url="http://2.gravatar.com/avatar/e4a1b4bf6865eddd0edfe8cb90361c84?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">ferruccio</media:title>
		</media:content>
	</item>
		<item>
		<title>Dynamic C++</title>
		<link>https://tlzprgmr.wordpress.com/2009/06/15/dynamic-c/</link>
		<comments>https://tlzprgmr.wordpress.com/2009/06/15/dynamic-c/#comments</comments>
		<pubDate>Tue, 16 Jun 2009 03:01:10 +0000</pubDate>
		<dc:creator><![CDATA[ferruccio]]></dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Dynamic-Typing]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[c++ programming dynamic-typing]]></category>

		<guid isPermaLink="false">http://the-lazy-programmer.com/blog/?p=70</guid>
		<description><![CDATA[A while back, I started building a PDF parser in C++. I had been using the Adobe PDF IFilter to extract text from PDF files in order to index the content, but I wanted to be able to be able to also extract formatting information so I dug into the PDF format. The PDF format [&#8230;]<img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=70&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>A while back, I started building a PDF parser in C++. I had been using the Adobe PDF IFilter to extract text from PDF files in order to index the content, but I wanted to be able to be able to also extract formatting information so I dug into the PDF format. The PDF format itself is fairly easy to parse, but the contents can be quite complex.</p>
<p>The PDF format consists of a series of objects, expressed in a simple syntax based on PostScript. There are primitives such as strings and numbers, and there are collections (arrays and dictionaries) which can contain both primitives and containers. You can see how things quickly become complicated when you have dictionaries containing arrays containing other complex objects.</p>
<p><span id="more-70"></span>So, I built a parser which would collect a stream of objects into a data structure for further processing. Since there was no way to know ahead of time the shape of the final structure, I used Boost’s variant library to contain each object. An object could be a primitive type or a shared pointer to an STL vector or map, depending on the underlying structure. The STL collections contained the same object class, so the resulting structure could be arbitrarily  complex.</p>
<p>After I got the basic parser working, I realized that I had implemented a dynamic typing system for C++ . . . poorly. Even though you could build these complex and dynamic data structures at runtime, the syntax necessary to manipulate them was a bit ugly. For  example, if you had an object (named ‘o’) that happened to be an array and you wanted to access the second element, which happened to be a string the syntax would be:</p>
<div>
<pre class="csharpcode">std::<span class="kwrd">string</span> s = (*o)[1];</pre>
</div>
<p>Not exactly horrible, but it could be cleaner.</p>
<p>It also seemed like a good project on its own, so I tore it out of the PDF parser and rewrote it. Twice. I called the class ‘var’ so that the syntax for declaring a dynamic object would look familiar to anyone used a dynamic language. i.e. you could say:</p>
<div>
<pre class="csharpcode">var name = <span class="str">"fred"</span>;
var age = 35;</pre>
</div>
<p>But I made a mistake in trying to make var a subclass of boost::variant&lt;…&gt;. I had the same issues getting the usage syntax under control. On my second attempt, I made the variant a private member of the var class and explicitly defined every supported operator. This made it simpler and more intuitive to use. The previous example became:</p>
<div>
<pre class="csharpcode">std::<span class="kwrd">string</span> s = o[1];</pre>
</div>
<p>Also, because I was focused on building a stand-alone dynamic type system rather than a data structure to support another project, I put a bit more thought into making object initialization easier. For example you can do this:</p>
<div>
<pre class="csharpcode">var a = new_array(1)(2)(2.5)(<span class="str">"hello"</span>)(new_dict(<span class="str">"name"</span>, <span class="str">"fred"</span>)(<span class="str">"age"</span>, 35));</pre>
</div>
<p>which creates a five element array named ‘a’ which contains two integers (1 and 2), a double (2.5), a string (“hello”) and a dictionary with two name-value pairs. Note that in a dictionary both the name and the value can be any type.</p>
<p>There is also a null type, represented by a $. The default value of any uninitialized var is $, but you can set it explicitly:</p>
<div>
<pre class="csharpcode">var name = $;</pre>
</div>
<p>I picked $ because it seems to be supported by many C++ compilers as a valid character in a variable name, but is not frequently used. It stands out.</p>
<p>There is one issue with null values that I haven’t resolved. If you try to retrieve a dictionary value whose key does not exist, it will return a null value, but it is perfectly valid to place a null value into a dictionary. e.g:</p>
<div>
<pre class="csharpcode">var d = new_dict(<span class="str">"a"</span>, <span class="str">"xxx"</span>)(<span class="str">"b"</span>, $);
cout &lt;&lt; d[<span class="str">"a"</span>] &lt;&lt; endl; <span class="rem">// prints: xxx</span>
cout &lt;&lt; d[<span class="str">"b"</span>] &lt;&lt; endl; // prints: $
cout &lt;&lt; d[<span class="str">"c"</span>] &lt;&lt; endl; // prints: $</pre>
</div>
<p>When operator[] returns $ on a dictionary, you don’t know if it was because the item didn’t exist or it existed but was $. What’s worse is that if it didn’t exist before calling operator[], it would exist afterwards (and be set to $). This is a consequence of the fact that operator[] returns a var&amp;. It has no idea if it’s being used as an l-value or an r-value, so it has to create the instance in case it is being used as an l-value. i.e.</p>
<div>
<pre class="csharpcode">d[<span class="str">"e"</span>] = 1;</pre>
</div>
<p>You can down load dynamic-cpp from Google Code at: <a href="http://code.google.com/p/dynamic-cpp/" target="_blank">http://code.google.com/p/dynamic-cpp/</a></p>
<p>To use it, you need the following code:</p>
<div>
<pre class="csharpcode">#include <span class="str">"dynamic.h"</span>

<span class="kwrd">using</span> <span class="kwrd">namespace</span> dynamic;</pre>
</div>
<p>Also, you need Boost. I’ve been using 1.37.0, but older versions should work as well. You need to build the project and link against the resulting static library. The code is platform independent but so far I have only Visual Studio project files. I will try to resolve that soon.</p>
<p>It comes with a suite of unit tests which will give you a better idea of its capabilities.</p>
<p>Let me know if you find something useful to do with it.</p><br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tlzprgmr.wordpress.com/70/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tlzprgmr.wordpress.com/70/" /></a> <img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=70&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://tlzprgmr.wordpress.com/2009/06/15/dynamic-c/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e4a1b4bf6865eddd0edfe8cb90361c84?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">ferruccio</media:title>
		</media:content>
	</item>
		<item>
		<title>&#060;XAML fest&#062;</title>
		<link>https://tlzprgmr.wordpress.com/2009/05/28/xaml-fest/</link>
		<pubDate>Thu, 28 May 2009 12:01:00 +0000</pubDate>
		<dc:creator><![CDATA[ferruccio]]></dc:creator>
				<category><![CDATA[/NET]]></category>
		<category><![CDATA[.net xaml silverlight blend]]></category>

		<guid isPermaLink="false">http://the-lazy-programmer.com/blog/?p=67</guid>
		<description><![CDATA[I just finished XAML fest, a two day introduction to SilverLight, XAML and Expression Blend.  The event was held at Microsoft’s New England R&#38;D  Center in Cambridge,  Massachusetts. The class centered around building a small web app using SilverLight. A lot of time was spent learning how to use Blend to build user interfaces. Having [&#8230;]<img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=67&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I just finished XAML fest, a two day introduction to SilverLight, XAML and Expression Blend.  The event was held at Microsoft’s New England R&amp;D  Center in Cambridge,  Massachusetts. The class centered around building a small web app using SilverLight. A lot of time was spent learning how to use Blend to build user interfaces.</p>
<p>Having spent a good portion of my career building Windows apps, I&#8217;ve had the opportunity to create UIs using the Win32 API, OWL, MFC, WTL and wxWidgets. I&#8217;ve dabbled in WPF but never did much with it since I&#8217;ve been spending most of my free time tinkering with Cocoa and Cocoa-Touch. What I really like about using XAML is that you can lay out an entire interface, including a lot of behavior without writing a single line of code.</p>
<p><span id="more-67"></span></p>
<p>If you really want to, you can lay out the entire interface in XAML directly. But, if you’re like me and can’t stomach working with XML except for making minor tweaks here and there then Blend is a great tool to have in your design toolkit.</p>
<p>Prior to this, I had no idea what Blend was. I saw it on the MSDN subscriber downloads site, but it wasn’t clear to me exactly what it was. It was obviously some kind of design tool, but the description on the site made it sound more like a PhotoShop or Illustrator competitor than a UI design tool.</p>
<p>Well, it <em>is</em> a UI design tool. A very powerful if not always intuitive one at that.  It complements Visual Studio nicely. The intent is that a designer would use Blend to design the interface and a programmer would use Visual Studio to implement the actual application. You can open the same solution (.sln) files with either product, although you need to be careful if you open the same solution with both products at once. Which version of a file is on disk depends on who saved last.</p>
<p>You can build and run solutions with Blend and you can also make UI changes in Visual Studio, but you will usually want to use each product for the task is more suited to do.</p>
<p>If you’re interested in building SilverLight or WPF apps (Blend supports those too), I would recommend attending one of these sessions. If you can’t get to one, they also have them online. Google <a href="http://www.google.com/search?hl=en&amp;q=xaml+fest&amp;aq=f&amp;oq=&amp;aqi=g3" target="_blank">xaml fest</a> to find the next one.</p><br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tlzprgmr.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tlzprgmr.wordpress.com/67/" /></a> <img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=67&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
		
		<media:content url="http://2.gravatar.com/avatar/e4a1b4bf6865eddd0edfe8cb90361c84?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">ferruccio</media:title>
		</media:content>
	</item>
		<item>
		<title>A Python snippet for reading binary data</title>
		<link>https://tlzprgmr.wordpress.com/2009/04/05/a-python-snippet-for-reading-binary-data/</link>
		<comments>https://tlzprgmr.wordpress.com/2009/04/05/a-python-snippet-for-reading-binary-data/#comments</comments>
		<pubDate>Mon, 06 Apr 2009 00:31:00 +0000</pubDate>
		<dc:creator><![CDATA[ferruccio]]></dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://the-lazy-programmer.com/blog/?p=64</guid>
		<description><![CDATA[I’ve been experimenting using Python to read data from binary files and started to notice the following pattern in my code. Read a block of binary data. Use struct.unpack() to break out individual fields. Create a dictionary from those fields using the appropriate key names. So, let’s suppose I needed to read a block which [&#8230;]<img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=64&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I’ve been experimenting using Python to read data from binary files and started to notice the following pattern in my code.</p>
<ol>
<li>Read a block of binary data.</li>
<li>Use struct.unpack() to break out individual fields.</li>
<li>Create a dictionary from those fields using the appropriate key names.</li>
</ol>
<p><span id="more-64"></span></p>
<p>So, let’s suppose I needed to read a block which contained a name (20 characters), an age (unsigned integer) and a salary (float). The code might look something like this:</p>
<div>
<pre class="csharpcode">import <span class="kwrd">struct</span>

(name, age, salary) = <span class="kwrd">struct</span>.unpack(<span class="str">"&lt; 20s I f"</span>, src.read(28))
record = {<span class="str">'name'</span> : name, <span class="str">'age'</span> : age, <span class="str">'salary'</span> : salary}</pre>
</div>
<p>That’s not bad, but it starts getting tedious to have to calculate the size of the block and construct the dictionary manually each time, so I wrote a small function to do all that automatically:</p>
<div>
<pre class="csharpcode">import <span class="kwrd">struct</span>

def readStruct(src, format, names):
    s = {}
    <span class="kwrd">for</span> nv <span class="kwrd">in</span> zip(names, <span class="kwrd">struct</span>.unpack(format, src.read(<span class="kwrd">struct</span>.calcsize(format)))):
        s[nv[0]] = nv[1]
    <span class="kwrd">return</span> s</pre>
</div>
<p>The code to read the record from the previous example then becomes:</p>
<div>
<pre class="csharpcode">record = readStruct(src, <span class="str">"&lt; 20s I f"</span>, (<span class="str">'name'</span>, <span class="str">'age'</span>, <span class="str">'salary'</span>))</pre>
</div>
<p>It’s a small change, but it has made working with binary files easier and less error-prone. The next step will be to combine the format and names parameters into a single format string that has the names embedded in it. We’re going to use regular expressions to achieve that goal.</p>
<p>The updated code is:</p>
<div>
<pre class="csharpcode">import <span class="kwrd">struct</span>
import re

def readStruct(src, format):
    rex = re.compile(<span class="str">"\{([a-zA-Z_]+)\}"</span>)
    names = rex.findall(format)
    format = rex.sub(<span class="str">""</span>, format)
    s = {}
    <span class="kwrd">for</span> nv <span class="kwrd">in</span> zip(names, <span class="kwrd">struct</span>.unpack(format, src.read(<span class="kwrd">struct</span>.calcsize(format)))):
        s[nv[0]] = nv[1]
    <span class="kwrd">return</span> s</pre>
</div>
<p>and the previous example now becomes:</p>
<div>
<pre class="csharpcode">record = readStruct(src, <span class="str">"&lt; {name} 20s {age} I {salary} f"</span>)</pre>
</div>
<p>Which, I think is a lot easier to write and read. Note that you don’t have to interleave the formatting and name strings. You could just as easily have written the format string as “&lt;20sIf{name}{age}{salary}” but I think interleaving them makes their use much clearer.</p><br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tlzprgmr.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tlzprgmr.wordpress.com/64/" /></a> <img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=64&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://tlzprgmr.wordpress.com/2009/04/05/a-python-snippet-for-reading-binary-data/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e4a1b4bf6865eddd0edfe8cb90361c84?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">ferruccio</media:title>
		</media:content>
	</item>
		<item>
		<title>Returning multiple values from a function in C++</title>
		<link>https://tlzprgmr.wordpress.com/2009/01/05/returning-multiple-values-from-a-function-in-c/</link>
		<comments>https://tlzprgmr.wordpress.com/2009/01/05/returning-multiple-values-from-a-function-in-c/#comments</comments>
		<pubDate>Tue, 06 Jan 2009 03:22:26 +0000</pubDate>
		<dc:creator><![CDATA[ferruccio]]></dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Boost]]></category>
		<category><![CDATA[cplusplus]]></category>

		<guid isPermaLink="false">http://the-lazy-programmer.com/blog/?p=55</guid>
		<description><![CDATA[Ideally all functions should return just one value. There are many times, however, when returning more than one value makes a function so much more convenient. The classic example of this convenience is file input. When we read data from a file we want to know two things: Did we reach the end of the [&#8230;]<img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=55&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Ideally all functions should return just one value. There are many times, however, when returning more than one value makes a function so much more convenient. The classic example of this convenience is file input. When we read data from a file we want to know two things: Did we reach the end of the file? and if not, what is the next piece of data from the file.</p>
<p>Sometimes, we can encode multiple return values into one. For many of us, the first C idiom we learned from K&amp;R is processing input a character at a time:</p>
<div>
<pre class="csharpcode"><span class="kwrd">int</span> ch;
<span class="kwrd">while</span> ((ch = getchar()) != EOF) {
    <span class="rem">// do character processing...</span>
}</pre>
</div>
<p>This works because the EOF macro was set to something outside the range of valid characters (usually -1). While this approach can work fairly well for simple cases, it quickly breaks down as the types we wish to return get more complex.</p>
<p><span id="more-55"></span></p>
<p>One way to return multiple values is to return one value through the function return mechanism and to pass pointers or references to objects which will receive the additional parameters as additional arguments to the function. For the sake of example, we are going to create a simple function which returns a single line of text from an input stream. This function will take one input parameter, the input stream, and return two values. The first value will be a boolean to indicate success and the second value will be the string that was read. Using the approach just described, we could code it up as:</p>
<div>
<pre class="csharpcode"><span class="kwrd">bool</span> readline(istream&amp; <span class="kwrd">is</span>, <span class="kwrd">string</span>&amp; line)
{
    <span class="kwrd">if</span> (<span class="kwrd">is</span>.eof())
        <span class="kwrd">return</span> <span class="kwrd">false</span>;
    getline(<span class="kwrd">is</span>, line);
    <span class="kwrd">return</span> <span class="kwrd">true</span>;
}</pre>
<p>And we would call it like this:</p>
<div>
<pre class="csharpcode"><span class="kwrd">string</span> line;
<span class="kwrd">while</span> (readline(ss, line))
    cout &lt;&lt; line &lt;&lt; endl;</pre>
</div>
<p>So, what&#8217;s wrong with this approach?</p>
<p>There&#8217;s a couple of issues.</p>
<ol>
<li>The first issue is mostly aesthetic. When we write functions, the output values are on the left and the input values go on the right. Now we have output values as part of the parameter list. We can document the function to indicate that line is an output parameter, but we aren&#8217;t going to document every call.</li>
<li>The second issue is that because all the output values are independent of each other, there is no way, at compile time, to enforce that every output parameter has been set to something. If you forgot to write a return statement in a function, the compiler will let you know. It would be nice to have the same error checking for all output values.</li>
</ol>
<p>Another approach is to return a struct which contains all the return values. Our line reading function now becomes:</p>
<div>
<div>
<pre class="csharpcode"><span class="kwrd">struct</span> line_ret
{
    <span class="kwrd">bool</span>    success;
    <span class="kwrd">string</span>  line;
};

line_ret readline(istream&amp; <span class="kwrd">is</span>)
{
    line_ret lr = { <span class="kwrd">false</span>, <span class="str">""</span> };
    <span class="kwrd">if</span> (!<span class="kwrd">is</span>.eof()) {
        lr.success = <span class="kwrd">true</span>;
        getline(<span class="kwrd">is</span>, lr.line);
    }
    <span class="kwrd">return</span> lr;
}</pre>
</div>
<p>And we would call it with:</p>
<div>
<pre class="csharpcode"><span class="kwrd">for</span> (;;) {
    line_ret lr = readline(ss);
    <span class="kwrd">if</span> (!lr.success) <span class="kwrd">break</span>;
    cout &lt;&lt; lr.line &lt;&lt; endl;
}</pre>
</div>
<p>At first this seems like a reasonable approach. The problem here is that we needed to define a struct whose only use is to represent the return values from this function. Structs should be used to hold logically related items. A good rule of thumb is if a struct (or class, obviously) doesn&#8217;t already exist, don&#8217;t create it just to contain multiple return values.</p>
<p>The last approach (and the whole point of this post) is to use tuples. I am going to demonstrate the same example using the <a href="http://www.boost.org/doc/libs/1_37_0/libs/tuple/doc/tuple_users_guide.html" target="_blank">Boost.Tuple</a> library but, if your compiler supports it, you could just as easily use TR1 tuples. They are the same thing. Using tuples, our code now looks like:</p>
<div>
<div>
<pre class="csharpcode">#include &lt;boost/tuple/tuple.hpp&gt;

<span class="kwrd">using</span> <span class="kwrd">namespace</span> boost;

tuple&lt;<span class="kwrd">bool</span>,<span class="kwrd">string</span>&gt; readline(istream&amp; <span class="kwrd">is</span>)
{
    <span class="kwrd">if</span> (<span class="kwrd">is</span>.eof()) <span class="kwrd">return</span> tuple&lt;<span class="kwrd">bool</span>,<span class="kwrd">string</span>&gt;(<span class="kwrd">false</span>);
    <span class="kwrd">string</span> line;
    getline(<span class="kwrd">is</span>, line);
    <span class="kwrd">return</span> tuple&lt;<span class="kwrd">bool</span>,<span class="kwrd">string</span>&gt;(<span class="kwrd">true</span>, line);
}</pre>
</div>
</div>
<p>This version returns a tuple which consists of a bool an a string. Note that the failure case has only the boolean in the return statement. Since the string is not provided, the default string constructor will be called to create an empty string which will be returned. We could call this function like this:</p>
<div>
<pre class="csharpcode"><span class="kwrd">for</span> (;;) {
    tuple&lt;<span class="kwrd">bool</span>,<span class="kwrd">string</span>&gt; ret = readline(ss);
    <span class="kwrd">if</span> (!ret.get&lt;0&gt;()) <span class="kwrd">break</span>;
    cout &lt;&lt; ret.get&lt;1&gt;() &lt;&lt; endl;
}</pre>
<p>The get&lt;n&gt;() syntax returns the nth member of a tuple. While this works, it&#8217;s not very clear. Fortunately, you can use a tier (pronounce it &#8220;tire&#8221; instead of &#8220;tear&#8221; and the name makes much more sense) to help out with that:</p>
<div>
<pre class="csharpcode"><span class="kwrd">for</span> (;;) {
    <span class="kwrd">bool</span> success;
    <span class="kwrd">string</span> line;
    tie(success, line) = readline(ss);
    <span class="kwrd">if</span> (!success) <span class="kwrd">break</span>;
    cout &lt;&lt; line &lt;&lt; endl;
}</pre>
</div>
<p>The tier ties success with the first tuple item and line with the second tuple item. That makes the resulting code much easier to read and we get compile-time checking for all the values we&#8217;re returning.</p></div>
</div>
</div><br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/tlzprgmr.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/tlzprgmr.wordpress.com/55/" /></a> <img alt="" border="0" src="https://pixel.wp.com/b.gif?host=tlzprgmr.wordpress.com&#038;blog=11950566&#038;post=55&#038;subd=tlzprgmr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://tlzprgmr.wordpress.com/2009/01/05/returning-multiple-values-from-a-function-in-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e4a1b4bf6865eddd0edfe8cb90361c84?s=96&#38;d=https%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">ferruccio</media:title>
		</media:content>
	</item>
	</channel>
</rss>
