<?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#"
	>

<channel>
	<title>Strong types Archives - Fluent C++</title>
	<atom:link href="https://www.fluentcpp.com/category/strong-types/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.fluentcpp.com/category/strong-types/</link>
	<description>Jonathan Boccara&#039;s blog</description>
	<lastBuildDate>Wed, 18 Nov 2020 10:27:43 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.5.4</generator>
<site xmlns="com-wordpress:feed-additions:1">214950964</site>	<item>
		<title>Strong Types for Safe Indexing in Collections &#8211; Part 2</title>
		<link>https://www.fluentcpp.com/2021/11/04/strong-types-for-safe-indexing-in-collections-part-2/</link>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Thu, 04 Nov 2021 01:00:24 +0000</pubDate>
				<category><![CDATA[Strong types]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[index]]></category>
		<category><![CDATA[lvalue]]></category>
		<category><![CDATA[proxy]]></category>
		<category><![CDATA[reference]]></category>
		<category><![CDATA[rvalue]]></category>
		<category><![CDATA[strong types]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=6243</guid>

					<description><![CDATA[<p>In the previous article on strong types, we set out to find how to use strong types for safe indexing in collections. More precisely, if we have two vectors with two indices to access them, how can we use strong types to make sure we use the right index for the right vector, and that [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2021/11/04/strong-types-for-safe-indexing-in-collections-part-2/">Strong Types for Safe Indexing in Collections &#8211; Part 2</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In the <a href="https://www.fluentcpp.com/2021/10/31/strong-types-for-safe-indexing-in-collections-part-1/">previous article</a> on strong types, we set out to find how to use strong types for safe indexing in collections.</p>
<p>More precisely, if we have two vectors with two indices to access them, how can we use strong types to make sure we use the right index for the right vector, and that we don&#8217;t swap them by mistake?</p>
<p>In other terms, if we have two collections:</p>
<pre class="lang:c++ decode:true">std::vector&lt;int&gt; foos = {1, 2, 3};
std::vector&lt;int&gt; bars = {10, 20};</pre>
<p>And we create two separate indices by using strong types:</p>
<pre class="lang:c++ decode:true">using FooIndex = NamedType&lt;size_t, struct FooTag, PreIncrementable, Comparable&gt;;
using BarIndex = NamedType&lt;size_t, struct BarTag, PreIncrementable, Comparable&gt;;</pre>
<p>Those are two different types wrapping a <code>size_t</code> and that can be incremented and compared.</p>
<p>How can we make this first piece of code compile:</p>
<pre class="lang:c++ decode:true ">for (FooIndex fooIndex = FooIndex{0}; fooIndex &lt; FooIndex{foos.size()}; ++fooIndex)
{
    for (BarIndex barIndex = BarIndex{0}; barIndex &lt; BarIndex{bars.size()}; ++barIndex)
    {
        std::cout &lt;&lt; foos[fooIndex] &lt;&lt; '-' &lt;&lt; bars[barIndex] &lt;&lt; '\n'; // ok, correct indices
    }
}</pre>
<p>And how to make this one trigger a compilation error?</p>
<pre class="lang:c++ decode:true ">for (FooIndex fooIndex = FooIndex{0}; fooIndex &lt; FooIndex{foos.size()}; ++fooIndex)
{
    for (BarIndex barIndex = BarIndex{0}; barIndex &lt; BarIndex{bars.size()}; ++barIndex)
    {
        std::cout &lt;&lt; foos[barIndex] &lt;&lt; '-' &lt;&lt; bars[fooIndex] &lt;&lt; '\n'; // oops, wrong indices!
    }
}</pre>
<p>In the <a href="https://www.fluentcpp.com/2021/10/31/strong-types-for-safe-indexing-in-collections-part-1/">previous article</a> we saw how to reuse the code of <code>std::vector</code> to implement a new data structure with a custom <code>operator[]</code>. We&#8217;ll see now another approach: how to use a proxy of a standard <code>std::vector</code> with a custom <code>operator[]</code>.</p>
<h3><span style="color: #ff6600;">Using a proxy: the simple case</span></h3>
<p>Using a proxy consists in storing a reference to the vector, and providing an <code>operator[]</code> with a custom interface that calls the normal <code>operator[]</code> of <code>std::vector</code>:</p>
<pre class="lang:c++ decode:true">template&lt;typename T, typename Index&gt;
class StrongIndexAccess
{
public:
    explicit StrongIndexAccess(std::vector&lt;T&gt; const&amp; vector) : vector_(vector){}

    typename std::vector&lt;T&gt;::const_reference operator[](Index pos) const
    {
        return vector_[pos.get()];
    }

private:
    std::vector&lt;T&gt; vector_;
};</pre>
<p>We can then create two different <code>StrongIndexAccess</code> by using the two strongly typed indices:</p>
<pre class="lang:c++ decode:true ">auto indexedFoos = StrongIndexAccess&lt;int, FooIndex&gt;(foos);
auto indexedBars = StrongIndexAccess&lt;int, BarIndex&gt;(bars);</pre>
<p>Then the following piece of code compiles:</p>
<pre class="lang:c++ decode:true">for (FooIndex fooIndex = FooIndex{0}; fooIndex &lt; FooIndex{foos.size()}; ++fooIndex)
{
    for (BarIndex barIndex = BarIndex{0}; barIndex &lt; BarIndex{bars.size()}; ++barIndex)
    {
        std::cout &lt;&lt; indexedFoos[fooIndex] &lt;&lt; '-' &lt;&lt; indexedBars[barIndex] &lt;&lt; '\n';
    }
}</pre>
<p>And this one doesn&#8217;t:</p>
<pre class="lang:c++ decode:true ">for (FooIndex fooIndex = FooIndex{0}; fooIndex &lt; FooIndex{foos.size()}; ++fooIndex)
{
    for (BarIndex barIndex = BarIndex{0}; barIndex &lt; BarIndex{bars.size()}; ++barIndex)
    {
        std::cout &lt;&lt; indexedFoos[barIndex] &lt;&lt; '-' &lt;&lt; indexedBars[fooIndex] &lt;&lt; '\n';
    }
}</pre>
<p>This is exactly what we wanted. Are we done then?</p>
<p>The above code works well for const references, which don&#8217;t allow modifying the values inside of the vector. To allow it we need to support non const references.</p>
<p>Also, our above code doesn&#8217;t support taking a reference on an incoming temporary vector:</p>
<pre class="lang:c++ decode:true ">auto indexedFoos = StrongIndexAccess&lt;int, FooIndex&gt;(std::vector&lt;int&gt;{1, 2, 3});
auto indexedBars = StrongIndexAccess&lt;int, BarIndex&gt;(std::vector&lt;int&gt;{10, 20});</pre>
<p>The code as we wrote it will compile, but as soon as we try to access the values through <code>StrongIndexAccess</code>, we get to undefined behaviour, typically with the application crashing, because we&#8217;re accessing a destroyed object.</p>
<p>We need to make our <code>StrongIndexAccess</code> support those two additional cases, and this is where the fun begins.</p>
<h3><span style="color: #ff6600;">Handling non const, lvalue and rvalue references</span></h3>
<p>Before writing code, let&#8217;s decide on how to handle the tree cases of incoming values:</p>
<ul>
<li>const lvalue reference: <code>std::vector&lt;T&gt; const&amp; vector</code></li>
<li>non const lvalue reference: <code>std::vector&lt;T&gt;&amp; vector</code></li>
<li>non const rvalue reference: <code>std::vector&lt;T&gt;&amp;&amp; vector</code></li>
</ul>
<p>We don&#8217;t include const rvalue references because they are virtually never used.</p>
<p>In the first two cases, with a lvalue reference, we can use the same idea as in the initial code. The source value being an lvalue, we know it&#8217;s going to stick around for some time before being destroyed, so we can just keep a reference to it. The reference has to be const or non const depending on the incoming value.</p>
<p>In the case of the rvalue though, we can&#8217;t just keep a reference: the incoming value is about to be destroyed, or is being moved from, which means in either case that we don&#8217;t want to access afterwards.</p>
<p>Another way then is to keep the whole value inside of our <code>StrongIndexAccess</code>, only for rvalues. Indeed an rvalue, especially of type <code>std::vector</code>, is made to be moved inside of our class.</p>
<p>In summary, here is what we want to do based on the type of the incoming value:</p>
<ul>
<li>const lvalue reference: keep a const lvalue reference</li>
<li>non const lvalue reference: keep a non const lvalue reference</li>
<li>non const rvalue reference: keep the whole value</li>
</ul>
<h4><span style="color: #ff6600;">The implementation</span></h4>
<p>This implies that the type of our data member depends on the incoming type to the constructor of <code>StrongIndexAccess</code>. C++ doesn&#8217;t allow to do that, but we can get away with something equivalent by using <code>std::variant</code>.</p>
<p>So we want a <code>std::variant&lt;std::vector&amp;, std::vector const&amp;, std::vector&gt;</code> as a member, or something like that, and be able to get a const or non const reference on this when we need it in <code>operator[]</code>.</p>
<p>This is not something straightforward to implement (although not very difficult) especially since <code>std::variant</code> does not accept reference types.</p>
<p>Luckily, we&#8217;ve already done all the work when we saw How to Store an lvalue or an rvalue in the Same Object.</p>
<p>Let&#8217;s reuse our code from back then, with the <code>Storage</code> type and its accessors <code>getReference</code> and <code>getConstReference</code>. We can just initialise the data member of type <code>Storage</code> depending on the incoming value in the constructor:</p>
<pre class="lang:c++ decode:true ">template&lt;typename T, typename Index&gt;
class StrongIndexAccess
{
public:
    explicit StrongIndexAccess(std::vector&lt;T&gt;&amp; vector) : vector_(NonConstReference(vector)){}
    explicit StrongIndexAccess(std::vector&lt;T&gt; const&amp; vector) : vector_(ConstReference(vector)){}
    explicit StrongIndexAccess(std::vector&lt;T&gt;&amp;&amp; vector) : vector_(Value(std::move(vector))){}

    typename std::vector&lt;T&gt;::reference operator[](Index pos)
    {
        auto&amp; vector = getReference(vector_);
        return vector[pos.get()];
    }

    typename std::vector&lt;T&gt;::const_reference operator[](Index pos) const
    {
        auto const&amp; vector = getConstReference(vector_);
        return vector[pos.get()];
    }

private:
    Storage&lt;std::vector&lt;T&gt;&gt; vector_;
};</pre>
<p>If you&#8217;re curious about how <code>Storage</code> works exactly, have a look at <a href="https://www.fluentcpp.com/how-to-store-an-lvalue-or-an-rvalue-in-the-same-object/">this preview article</a>.</p>
<h3><span style="color: #ff6600;">Where to put the custom code</span></h3>
<p>In the <a href="https://www.fluentcpp.com/2021/10/31/strong-types-for-safe-indexing-in-collections-part-1/">previous article</a> we saw how to introduce another data structure than <code>std::vector</code> to achieve our purpose of customising <code>operator[]</code>. And in this article we&#8217;ve just seen how to introduce a proxy to support the custom <code>operator[]</code> without changing the data structure.</p>
<p>The drawback of the proxy is that you have two objects in the client code: the data structure and the proxy. Whereas by customising the data structure there is only the data structure to manipulate. But the advantage of the proxy is that it is a more modular solution.</p>
<p>All in all, I prefer the solution of the proxy. Which one do you prefer? Would you have solved the problem of strong indexing differently? Let me know in a comment!</p>
<h3>You will also like</h3>
<ul>
<li><a href="https://www.fluentcpp.com/2021/10/31/strong-types-for-safe-indexing-in-collections-part-1/">Strong Types for Safe Indexing in Collections &#8211; Part 1</a></li>
<li><a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/">Strong types for strong interfaces</a></li>
<li><a href="https://www.fluentcpp.com/2018/02/06/understanding-lvalues-rvalues-and-their-references/">Understanding lvalues, rvalues and their references</a></li>
<li><a href="https://www.fluentcpp.com/2020/06/26/implementing-a-universal-reference-wrapper/">A Universal Reference Wrapper</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2021%2F11%2F04%2Fstrong-types-for-safe-indexing-in-collections-part-2%2F&#038;t=Strong%20Types%20for%20Safe%20Indexing%20in%20Collections%20%E2%80%93%20Part%202&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2021%2F11%2F04%2Fstrong-types-for-safe-indexing-in-collections-part-2%2F&#038;p&#091;images&#093;&#091;0&#093;=&#038;p&#091;title&#093;=Strong%20Types%20for%20Safe%20Indexing%20in%20Collections%20%E2%80%93%20Part%202" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2021%2F11%2F04%2Fstrong-types-for-safe-indexing-in-collections-part-2%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2021%2F11%2F04%2Fstrong-types-for-safe-indexing-in-collections-part-2%2F&#038;title=Strong%20Types%20for%20Safe%20Indexing%20in%20Collections%20%E2%80%93%20Part%202" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2021/11/04/strong-types-for-safe-indexing-in-collections-part-2/">Strong Types for Safe Indexing in Collections &#8211; Part 2</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">6243</post-id>	</item>
		<item>
		<title>Strong Types for Safe Indexing in Collections &#8211; Part 1</title>
		<link>https://www.fluentcpp.com/2021/10/31/strong-types-for-safe-indexing-in-collections-part-1/</link>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Sun, 31 Oct 2021 01:00:22 +0000</pubDate>
				<category><![CDATA[Strong types]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[index]]></category>
		<category><![CDATA[strong types]]></category>
		<category><![CDATA[vector]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=6214</guid>

					<description><![CDATA[<p>Strong types make code safer and more expressive by using the type system to identify individual objects. For example, to instantiate a class Rectangle with a certain width and height, we could write this: Rectangle myRectangle{4, 5}; But then it isn&#8217;t clear for a reader of the code which of the two parameters is the [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2021/10/31/strong-types-for-safe-indexing-in-collections-part-1/">Strong Types for Safe Indexing in Collections &#8211; Part 1</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Strong types make code safer and more expressive by using the type system to identify individual objects.</p>
<p>For example, to instantiate a class <code>Rectangle</code> with a certain width and height, we could write this:</p>
<pre class="lang:c++ decode:true">Rectangle myRectangle{4, 5};</pre>
<p>But then it isn&#8217;t clear for a reader of the code which of the two parameters is the width and which one is the height. Which one is 4? Which one is 5?</p>
<p>This makes code difficult to understand, and difficult to get right too. Indeed, swapping the parameters by mistake is a common source of bugs.</p>
<p>An alternative is to introduce new types, <code>Width</code> and <code>Height</code>, and make the constructor accept them instead of primitive types:</p>
<pre class="lang:c++ decode:true ">Rectangle myRectangle{Width{4}, Height{5}};</pre>
<p>This makes the code much more expressive and safer.</p>
<p>Strong typing is a very rich topic (you can find <a href="https://www.fluentcpp.com/?s=strong+types">dozens of articles</a> on strong types on Fluent C++) and helps make code more expressive in many ways.</p>
<p>Let&#8217;s focus on one of those ways: using strong types for safe indexing in collections.</p>
<h3><span style="color: #ff6600;">Using the right index</span></h3>
<p>The need for &#8220;strong indexing&#8221; came from an issue raised in the <a href="https://github.com/joboccara/NamedType">NamedType</a> library (an implementation of strong types for C++): how can we use strong types to make sure to use the correct index when working with several collections?</p>
<p>Let&#8217;s use <code>std::vector</code> to represent the collections here. We have two vectors:</p>
<pre class="lang:c++ decode:true">std::vector&lt;int&gt; foos = {1, 2, 3};
std::vector&lt;int&gt; bars = {10, 20};</pre>
<p>And we&#8217;d like to have an index for each vector, that can <em>only </em>be used for that vector. This way, we make sure not to use an index with the wrong vector.</p>
<p>Let&#8217;s create two separate indices by using strong types:</p>
<pre class="lang:c++ decode:true">using FooIndex = NamedType&lt;size_t, struct FooTag, PreIncrementable, Comparable&gt;;
using BarIndex = NamedType&lt;size_t, struct BarTag, PreIncrementable, Comparable&gt;;</pre>
<p>Those are two different types wrapping a <code>size_t</code> and that can be incremented and compared.</p>
<p>Then we&#8217;d like this code to compile:</p>
<pre class="lang:c++ decode:true">for (FooIndex fooIndex = FooIndex{0}; fooIndex &lt; FooIndex{foos.size()}; ++fooIndex)
{
    for (BarIndex barIndex = BarIndex{0}; barIndex &lt; BarIndex{bars.size()}; ++barIndex)
    {
        std::cout &lt;&lt; foos[fooIndex] &lt;&lt; '-' &lt;&lt; bars[barIndex] &lt;&lt; '\n'; // ok, correct indices
    }
}</pre>
<p>And we would like the following code to fail to compile:</p>
<pre class="lang:c++ decode:true">for (FooIndex fooIndex = FooIndex{0}; fooIndex &lt; FooIndex{foos.size()}; ++fooIndex)
{
    for (BarIndex barIndex = BarIndex{0}; barIndex &lt; BarIndex{bars.size()}; ++barIndex)
    {
        std::cout &lt;&lt; foos[barIndex] &lt;&lt; '-' &lt;&lt; bars[fooIndex] &lt;&lt; '\n'; // oops, wrong indices!
    }
}</pre>
<p>How do we do this?</p>
<p>Unless we change the code of the implementation of a standard library, we can&#8217;t write the exact above pieces of code. Indeed, <code>std::vector</code>&#8216;s <code>operator[]</code> doesn&#8217;t take a <code>FooIndex</code> or a <code>BarIndex</code>, to begin with.</p>
<p>But we can adapt the code a little to make it valid. We&#8217;ll see two different ways:</p>
<ul>
<li>introducing a strongly indexed vector (this post),</li>
<li>creating a strongly indexed reference an a normal <code>std::vector</code> (the next post).</li>
</ul>
<h3><span style="color: #ff6600;">A strongly indexed vector</span></h3>
<p>What prevents us from writing the above code is that <code>std::vector</code> doesn&#8217;t have the interface we need: it doesn&#8217;t accept <code>FooIndex</code> and <code>BarIndex</code>. Let&#8217;s not use vector then, but introduce a new container instead!</p>
<p>On the other hand, it would be a shame to give up on everything vector provides, and code it up from scratch ourselves, just for the purpose of tweaking the <code>operator[]</code>.</p>
<p>It would be great to reuse <code>std::vector</code> for everything except <code>operator[]</code>.</p>
<p>There are at least three ways to do that: public inheritance, private inheritance and composition. Let&#8217;s start with public inheritance, that require the least code to write.</p>
<h4><span style="color: #ff6600;">Public inheritance</span></h4>
<p>To reuse all the interface of <code>std::vector</code>, we can inherit from it. Here is the code, we&#8217;ll explain it bit by bit just after:</p>
<pre class="lang:c++ decode:true">template&lt;typename T, typename Index&gt;
class StrongIndexVector : public std::vector&lt;T&gt;
{
public:
    StrongIndexVector() = default;
    explicit StrongIndexVector(typename std::vector&lt;T&gt;::size_type count, const T&amp; value = T()) : std::vector&lt;T&gt;(count, value) {}
    template&lt; class InputIt &gt;
    StrongIndexVector(InputIt first, InputIt last) : std::vector&lt;T&gt;(first, last) {}
    StrongIndexVector(std::initializer_list&lt;T&gt; init) : std::vector&lt;T&gt;(std::move(init)) {}

    typename std::vector&lt;T&gt;::reference operator[]( Index pos )
    {
        return std::vector&lt;T&gt;::operator[](pos.get());
    }

    typename std::vector&lt;T&gt;::const_reference operator[]( Index pos ) const
    {
        return std::vector&lt;T&gt;::operator[](pos.get());
    }
};</pre>
<p>Let&#8217;s start with the first line:</p>
<pre class="lang:c++ decode:true ">template&lt;typename T, typename Index&gt;</pre>
<p>Like <code>std::vector</code>, our class can store values of any type <code>T</code>. It also has a specific <code>Index</code> type, that would be in our initial example <code>FooIndex</code> or <code>BarIndex</code>.</p>
<p>Let&#8217;s skip to the end of the class:</p>
<pre class="lang:c++ decode:true ">    typename std::vector&lt;T&gt;::reference operator[]( Index pos )
    {
        return std::vector&lt;T&gt;::operator[](pos.get());
    }

    typename std::vector&lt;T&gt;::const_reference operator[]( Index pos ) const
    {
        return std::vector&lt;T&gt;::operator[](pos.get());
    }
};</pre>
<p>We use this index to achieve our purpose and have an <code>operator[]</code> that only works with the specific index. This <code>operator[]</code> hides the one of the base class <code>std::vector</code> (read Item 33 of <a href="https://www.amazon.com/gp/product/0321334876/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321334876&amp;linkCode=as2&amp;tag=fluentcpp-20&amp;linkId=c827183fcb052e6a805d39ee7d66095">Effective C++</a> to learn more about this mechanism).</p>
<p>The rest of the code allows to reuse everything else from <code>std::vector</code>:</p>
<pre class="lang:c++ decode:true">class StrongIndexVector : public std::vector&lt;T&gt;
{
public:
    StrongIndexVector() = default;
    explicit StrongIndexVector(typename std::vector&lt;T&gt;::size_type count, const T&amp; value = T()) : std::vector&lt;T&gt;(count, value) {}
    template&lt; class InputIt &gt;
    StrongIndexVector(InputIt first, InputIt last) : std::vector&lt;T&gt;(first, last) {}
    StrongIndexVector(std::initializer_list&lt;T&gt; init) : std::vector&lt;T&gt;(std::move(init)) {}</pre>
<p>The call site then looks like this:</p>
<pre class="lang:c++ decode:true">using FooIndex = fluent::NamedType&lt;size_t, struct FooTag, fluent::PreIncrementable, fluent::Comparable&gt;;
using BarIndex = fluent::NamedType&lt;size_t, struct BarTag, fluent::PreIncrementable, fluent::Comparable&gt;;

StrongIndexVector&lt;int, FooIndex&gt; foos = {1, 2, 3};
StrongIndexVector&lt;int, BarIndex&gt; bars = {10, 20};

for (FooIndex fooIndex = FooIndex{0}; fooIndex &lt; FooIndex{foos.size()}; ++fooIndex)
{
    for (BarIndex barIndex = BarIndex{0}; barIndex &lt; BarIndex{bars.size()}; ++barIndex)
    {
        std::cout &lt;&lt; foos[fooIndex] &lt;&lt; '-' &lt;&lt; bars[barIndex] &lt;&lt; '\n';
    }
}</pre>
<p>The first two lines create two strong types over a <code>size_t</code>, in order to have two different types of indices.</p>
<p>Although using public inheritance works here, it&#8217;s arguably not the optimal solution, because it has several drawbacks. If a <code>StrongIndexVector</code> is (implicitly) cast into a <code>std::vector</code>, then the native <code>operator[]</code> of <code>std::vector</code> is available again and we&#8217;re back to square one.</p>
<p>Also, this is less likely to happen but if a <code>StrongIndexVector</code> is dynamically allocated, then deleted through a pointer to its base class <code>std::vector</code>, then we get to undefined behaviour.</p>
<p><strong>Advantages:</strong></p>
<ul>
<li>Little code</li>
</ul>
<p><strong>Drawbacks:</strong></p>
<ul>
<li>Not ideal when cast to base class</li>
</ul>
<p>Let&#8217;s explore the alternative of private inheritance then.</p>
<h4><span style="color: #ff6600;">Private inheritance</span></h4>
<p>As Federico demonstrates in his post on <a href="https://www.fluentcpp.com/2020/08/28/use-private-inheritance-to-restrict-interfaces/">restricting interfaces</a>, private inheritance provides an interesting trade-off to reuse code in an expressive way.</p>
<p>By default, private inheritance doesn&#8217;t expose anything from the interface of the base class. We have to add back whatever we want to reuse from the base class with <code>using</code> declarations. In our case, we want to reuse everything except <code>operator[]</code>. And then we write our own <code>operator[]</code>(highlighted):</p>
<pre class="lang:c++ mark:13-21 decode:true">template&lt;typename T, typename Index&gt;
class StrongIndexVector : private std::vector&lt;T&gt;
{
public:
    StrongIndexVector() = default;
    explicit StrongIndexVector(typename std::vector&lt;T&gt;::size_type count, const T&amp; value = T()) : std::vector&lt;T&gt;(count, value) {}
    template&lt; class InputIt &gt;
    StrongIndexVector(InputIt first, InputIt last) : std::vector&lt;T&gt;(first, last) {}
    StrongIndexVector(std::initializer_list&lt;T&gt; init) : std::vector&lt;T&gt;(std::move(init)) {}
    StrongIndexVector(StrongIndexVector const&amp; other) = default;
    StrongIndexVector(StrongIndexVector&amp;&amp; other) = default;

    typename std::vector&lt;T&gt;::reference operator[]( Index pos )
    {
        return std::vector&lt;T&gt;::operator[](pos.get());
    }

    typename std::vector&lt;T&gt;::const_reference operator[]( Index pos ) const
    {
        return std::vector&lt;T&gt;::operator[](pos.get());
    }

    using typename std::vector&lt;T&gt;::value_type;
    using typename std::vector&lt;T&gt;::allocator_type;
    using typename std::vector&lt;T&gt;::size_type;
    using typename std::vector&lt;T&gt;::difference_type;
    using typename std::vector&lt;T&gt;::reference;
    using typename std::vector&lt;T&gt;::const_reference;
    using typename std::vector&lt;T&gt;::pointer;
    using typename std::vector&lt;T&gt;::const_pointer;
    using typename std::vector&lt;T&gt;::iterator;
    using typename std::vector&lt;T&gt;::const_iterator;
    using typename std::vector&lt;T&gt;::reverse_iterator;
    using typename std::vector&lt;T&gt;::const_reverse_iterator;

    StrongIndexVector&amp; operator=(StrongIndexVector const&amp; other) = default;
    StrongIndexVector&amp; operator=(StrongIndexVector&amp;&amp; other) = default;
    using std::vector&lt;T&gt;::operator=;

    using std::vector&lt;T&gt;::assign;
    using std::vector&lt;T&gt;::get_allocator;
    using std::vector&lt;T&gt;::at;
    using std::vector&lt;T&gt;::front;
    using std::vector&lt;T&gt;::back;
    using std::vector&lt;T&gt;::data;
    using std::vector&lt;T&gt;::begin;
    using std::vector&lt;T&gt;::cbegin;
    using std::vector&lt;T&gt;::end;
    using std::vector&lt;T&gt;::cend;
    using std::vector&lt;T&gt;::rbegin;
    using std::vector&lt;T&gt;::crbegin;
    using std::vector&lt;T&gt;::rend;
    using std::vector&lt;T&gt;::crend;
    using std::vector&lt;T&gt;::empty;
    using std::vector&lt;T&gt;::size;
    using std::vector&lt;T&gt;::max_size;
    using std::vector&lt;T&gt;::reserve;
    using std::vector&lt;T&gt;::capacity;
    using std::vector&lt;T&gt;::shrink_to_fit;
    using std::vector&lt;T&gt;::clear;
    using std::vector&lt;T&gt;::insert;
    using std::vector&lt;T&gt;::emplace;
    using std::vector&lt;T&gt;::erase;
    using std::vector&lt;T&gt;::push_back;
    using std::vector&lt;T&gt;::emplace_back;
    using std::vector&lt;T&gt;::pop_back;
    using std::vector&lt;T&gt;::resize;
    using std::vector&lt;T&gt;::swap;
};</pre>
<p>This can be a little unsettling as private inheritance is not so common in production code. But I don&#8217;t think this is a real drawback, since as we saw in the <a href="https://www.fluentcpp.com/2019/04/30/common-vocabulary-software-developers/">The Common Vocabulary of Software Developers</a>, we should level up to the standard coding techniques, and not the other way round.</p>
<p><strong>Advantages:</strong></p>
<ul>
<li>Not castable to base class</li>
</ul>
<p><strong>Drawbacks:</strong></p>
<ul>
<li>A bit long to write (but feel free to copy-paste!)</li>
</ul>
<h4><span style="color: #ff6600;">Composition</span></h4>
<p>Composition is the solution that is commonly seen as the most reasonable, because it doesn&#8217;t use inheritance and inheritance is generally frowned upon in design when it&#8217;s not absolutely necessary.</p>
<p>Composition consists in storing a <code>std::vector</code> as a data member of <code>StrongIndexVector</code>, and wrap each function of its interface. For example, for <code>push_back</code>, we&#8217;d write:</p>
<pre class="lang:c++ decode:true ">template&lt;typename T, typename Index&gt;
class StrongIndexVector
{
public:

    // ...

    void push_back(T const&amp; value)
    {
        vector_.push_back(value);
    }

    void push_back(T&amp;&amp; value)
    {
        vector_.push_back(std::move(value));
    }

    // ...
    
private:
    std::vector&lt;T&gt; vector_;
};
</pre>
<p>And we would also write our own version of <code>operator[]</code> as in the previous code using inheritance.</p>
<p>This represents loads of code, and I think it brings little more than private inheritance.</p>
<p><strong>Advantages:</strong></p>
<ul>
<li>More conventional</li>
</ul>
<p><strong>Disadvantages:</strong></p>
<ul>
<li>Loads of code</li>
</ul>
<h3><span style="color: #ff6600;">A strongly indexed reference</span></h3>
<p>So far we&#8217;ve seen how to design a container with a special <code>operator[]</code>. But there is another approach: using a proxy on a regular <code>std::vector</code>, and implement our <code>operator[]</code> on the proxy.</p>
<p>We&#8217;ve seen a lot today, and we&#8217;ll keep this for the next post. In the meantime I suggest that you implement that proxy idea on your own, because it&#8217;s a good C++ exercise. Don&#8217;t forget that the incoming vector could be <code>const</code> or not <code>const</code>, and that it can be an lvalue or an rvalue!</p>
<p>More on that in the next article. Stay tuned!</p>
<h3>You will also like</h3>
<ul>
<li><a href="https://www.fluentcpp.com/2019/07/26/strong-types-on-collections/">Strong Types on Collections</a></li>
<li><a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/">Strong types for strong interfaces</a></li>
<li><a href="https://www.fluentcpp.com/2020/08/28/use-private-inheritance-to-restrict-interfaces/">Use Private Inheritance to Restrict Interfaces</a></li>
<li><a href="https://www.fluentcpp.com/2019/04/30/common-vocabulary-software-developers/">The Common Vocabulary of Software Developers</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2021%2F10%2F31%2Fstrong-types-for-safe-indexing-in-collections-part-1%2F&#038;t=Strong%20Types%20for%20Safe%20Indexing%20in%20Collections%20%E2%80%93%20Part%201&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2021%2F10%2F31%2Fstrong-types-for-safe-indexing-in-collections-part-1%2F&#038;p&#091;images&#093;&#091;0&#093;=&#038;p&#091;title&#093;=Strong%20Types%20for%20Safe%20Indexing%20in%20Collections%20%E2%80%93%20Part%201" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2021%2F10%2F31%2Fstrong-types-for-safe-indexing-in-collections-part-1%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2021%2F10%2F31%2Fstrong-types-for-safe-indexing-in-collections-part-1%2F&#038;title=Strong%20Types%20for%20Safe%20Indexing%20in%20Collections%20%E2%80%93%20Part%201" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2021/10/31/strong-types-for-safe-indexing-in-collections-part-1/">Strong Types for Safe Indexing in Collections &#8211; Part 1</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">6214</post-id>	</item>
		<item>
		<title>Strong Types on Collections</title>
		<link>https://www.fluentcpp.com/2019/07/26/strong-types-on-collections/</link>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Fri, 26 Jul 2019 01:00:42 +0000</pubDate>
				<category><![CDATA[Strong types]]></category>
		<category><![CDATA[braces]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[strong type]]></category>
		<category><![CDATA[vector]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=4000</guid>

					<description><![CDATA[<p>Do we need a special strong type library for collections? Or can we strongly type collections like we do for any object? If you&#8217;re joining us right now and haven&#8217;t read the previous articles on strong types, long story short, a strong type is a type used instead of another one in order to add [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2019/07/26/strong-types-on-collections/">Strong Types on Collections</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Do we need a special strong type library for collections? Or can we strongly type collections like we do for any object?</p>
<p>If you&#8217;re joining us right now and haven&#8217;t read the previous articles on strong types, long story short, a strong type is a type used instead of another one in order to add meaning via its name.</p>
<p>Long story a little less short: check out this way to define a <a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/">strong type in C++ with a library</a> and that way to define one with <a href="https://www.fluentcpp.com/2018/04/06/strong-types-by-struct/">native C++ features</a>.</p>
<p>And long story long: here is the ever-growing series on strong types on Fluent C++:</p>
<ul>
<li><a href="https://www.fluentcpp.com/2016/12/05/named-constructors/" target="_blank" rel="noopener noreferrer">Strongly typed constructors</a></li>
<li><a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/" target="_blank" rel="noopener noreferrer">Strong types for strong interfaces</a></li>
<li><a href="https://www.fluentcpp.com/2017/03/06/passing-strong-types-reference-revisited/" target="_blank" rel="noopener noreferrer">Passing strong types by reference</a></li>
<li><a href="https://www.fluentcpp.com/2017/02/20/strong-lambdas-strong-generic-types/" target="_blank" rel="noopener noreferrer">Strong lambdas: strong typing over generic types</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/05/news-strong-types-are-free/" target="_blank" rel="noopener noreferrer">Good news: strong types are (mostly) free in C++</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/23/strong-types-inheriting-functionalities-from-underlying/" target="_blank" rel="noopener noreferrer">Inheriting functionalities from the underlying type</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/30/implementing-a-hash-function-for-strong-types/" target="_blank" rel="noopener noreferrer">Making strong types hashable</a></li>
<li><a href="https://www.fluentcpp.com/2018/02/02/strong-types-strong-interfaces-talk-meeting-cpp/">Strong Types For Strong Interfaces: my talk at Meeting C++</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/26/strong-types-conversions/" target="_blank" rel="noopener noreferrer">Converting strong units to one another</a></li>
<li><a href="https://www.fluentcpp.com/2017/08/08/metaclasses-ultimate-answer-strong-typing-c/" target="_blank" rel="noopener noreferrer">Metaclasses, the Ultimate Answer to Strong Typing in C++?</a></li>
<li><a href="https://www.fluentcpp.com/2017/11/07/calling-functions-methods-strong-types/">Calling functions and methods on strong types</a></li>
<li><a href="https://www.fluentcpp.com/2017/11/10/strong-types-multiple-return-values/">Using Strong Types to Return Multiple Values</a></li>
<li><a href="https://www.fluentcpp.com/2018/01/05/making-strong-types-implicitly-convertible/">Making strong types implicitly convertible</a></li>
<li><a href="https://www.fluentcpp.com/2018/01/09/strong-templates/">Strong templates</a></li>
<li><a href="https://www.fluentcpp.com/2018/01/16/strong-optionals/">Strong optionals</a></li>
<li><a href="https://www.fluentcpp.com/2018/04/06/strong-types-by-struct/">Getting the Benefits of Strong Typing in C++ at a Fraction of the Cost</a></li>
<li>Strong types on collections</li>
</ul>
<h3><span style="color: #ff6600;">Strong typing on a collection: motivating example</span></h3>
<p>As a motivating example to strongly type collections, consider the following class:</p>
<pre class="lang:c++ decode:true ">class Team
{
public:
    template&lt;typename... TEmployee&gt;
    Team(TEmployee&amp;&amp;... teamMembers) : teamMembers_{std::forward&lt;TEmployee&gt;(teamMembers)...} {}
    
    std::vector&lt;Employee&gt; const&amp; get() const { return teamMembers_; }
private:
    std::vector&lt;Employee&gt; teamMembers_;
};</pre>
<p>It represents a team of people, which is not much more than a vector of <code>Employee</code>s, but than we&#8217;d like to see tagged as &#8220;team&#8221; in the code that uses it.</p>
<p>This code is inspired (quite largely) from a piece of code I came across recently. It wasn&#8217;t about teams and employees, but that was the general gist of it.</p>
<p>Its purpose is to allow the nice following syntax:</p>
<pre class="lang:c++ decode:true">auto team1 = Team(Alice, Bob, Tom);
auto team2 = Team(Arthur, Trillian);</pre>
<p>Also, <code>Team</code> is a type that is different from <code>std::vector&lt;Employee&gt;</code>, and if there were another concept of grouping employees together, it would be yet another type, different from <code>Team</code>.</p>
<p>Granted, maybe there isn&#8217;t so many ways to group employees together. But if you replace <code>Employee</code> with <code>int</code>, then there are many more possible meanings to give to <code>std::vector&lt;int&gt;</code>, and it could be useful to make sure we don&#8217;t mix them up, by giving each one its specific type. A typical example of mixup is to pass several of them in the wrong order to a function.</p>
<p>All this works well for teams and for <code>int</code>s, but we can imagine that it would equally apply to other groups of stuff. It would be nice to make this code generic, and have a facility to strongly type collections.</p>
<p>We already have a library that performs strong typing on C++ objects: <a href="http://github.com/joboccara/NamedType"><code>NamedType</code></a>. Can it spare us from re-implementing the <code>Team</code> class?</p>
<h3><span style="color: #ff6600;">Strong typing on collections</span></h3>
<p>Let&#8217;s make an attempt to use <code>NamedType</code> here:</p>
<pre class="lang:c++ decode:true ">using Team = NamedType&lt;std::vector&lt;Employee&gt;, struct TeamTag&gt;;</pre>
<p>That&#8217;s a terser declaration. Now let&#8217;s have a look at the call site:</p>
<pre class="lang:c++ decode:true ">auto team1 = Team(std::vector&lt;Employee&gt;{Alice, Bob, Tom});
auto team2 = Team(std::vector&lt;Employee&gt;{Arthur, Trillian});
</pre>
<p>Ouch. It doesn&#8217;t look as nice as before, because of the <code>std::vector&lt;Employee&gt;</code> sticking out.</p>
<p>But before we thing of a way of chopping it off, let&#8217;s pause and reflect on whether it is good or bad to make the <code>std::vector</code> show after all.</p>
<p>Clearly, it wasn&#8217;t the intent of the initial code. Indeed, the purpose of <code>Team</code> was to encapsulate the raw collection behind a meaningful type. But on the other hand, maybe we do care that it&#8217;s a vector. Indeed, as advocated in <a href="https://www.amazon.com/gp/product/0201749629/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0201749629&amp;linkCode=as2&amp;tag=fluentcpp-20&amp;linkId=78089f99eb0e896b3eca4fb2b456166d">Effective STL</a> Item 2: &#8220;Beware the illusion of container-independent code.&#8221; So maybe showing that it&#8217;s a vector isn&#8217;t such a bad thing.</p>
<p>But on the other other hand, what else would you want it to be? Indeed, Herb Sutter and Andrei Alexandrescu advise to &#8220;Use vector by default&#8221;, in Item 76 of their popular <a href="https://www.amazon.com/gp/product/0321113586/ref=as_li_qf_asin_il_tl?ie=UTF8&amp;tag=fluentcpp-20&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=0321113586&amp;linkId=932f5d03f44afa6097ea988d365bd8cc">C++ Coding Standards</a>.</p>
<p>So there are pros and cons to make the vector show, but let&#8217;s assume that we would like to hide it. Is there a way to do it and have generic code?</p>
<h4><span style="color: #ff6600;">A <code>NamedVector</code>?</span></h4>
<p>One idea is to design a new class alongside <code>NamedType</code>, that would be dedicated to handling vectors:</p>
<pre class="lang:c++ decode:true">template &lt;typename T, typename Parameter&gt;
class NamedVector
{
public:
    template&lt;typename... TElement&gt;
    explicit NamedVector(TElement&amp;&amp;... elements) : collection_({std::forward&lt;TElement&gt;(elements)...}) {}

    std::vector&lt;T&gt;&amp; get() { return collection_; }
    std::vector&lt;T&gt; const&amp; get() const {return collection_; }

private:
    std::vector&lt;T&gt; collection_;
};</pre>
<p>To instantiate the <code>Team</code> type we would do:</p>
<pre class="lang:c++ decode:true">using Team = NamedVector&lt;Employee, struct TeamTag&gt;;
</pre>
<p>And we get the nice syntax back:</p>
<pre class="lang:c++ decode:true ">auto team1 = Team(Alice, Bob, Tom);
auto team2 = Team(Arthur, Trillian);</pre>
<p>But a generic class like <code>NamedVector</code> has drawbacks: first, there is already a generic class (<code>NamedType</code>) and it would be simpler if there were only one. And what&#8217;s more, we&#8217;ve made <code>NamedVector</code> but we would also need <code>NamedMap</code>, <code>NamedSet</code>, <code>NamedArray</code> and <code>NamedList</code> (er, ok, maybe not <code>NamedList</code>).</p>
<h4><span style="color: #ff6600;">A convenient constructor of <code>std::vector</code></span></h4>
<p>It turns out that we don&#8217;t need <code>NamedVector</code>, because a slight change to the code would make it compile, without showing the underlying <code>std::vector</code>:</p>
<pre class="lang:c++ decode:true ">using Team = NamedType&lt;std::vector&lt;Employee&gt;, struct TeamTag&gt;;

auto team1 = Team({Alice, Bob, Tom});
auto team2 = Team({Arthur, Trillian});</pre>
<p>How does this work? It relies on the constructor of <code>std::vector</code> that accepts an <code>std::initializer_list</code>. And this constructor is not <code>explicit</code>, so we don&#8217;t need to type <code>std::vector&lt;Employee&gt;</code> to instantiate it.</p>
<p>An additional pair of braces popped up, but it simplifies a lot the library code.</p>
<p>Have you already encountered the need for a strong vector? Which solution do you prefer: a dedicated <code>Team</code> class, a <code>NamedVector</code>, or a <code>NamedType</code> with <code>std::vector</code>&#8216;s implicit conversion? Do you have another solution?</p>
<h3>You may also like</h3>
<ul>
<li><a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/">Strong types for strong interfaces</a></li>
<li><a href="https://www.fluentcpp.com/2018/01/30/most-vexing-parse/">The Most Vexing Parse: How to Spot It and Fix It Quickly</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2019%2F07%2F26%2Fstrong-types-on-collections%2F&#038;t=Strong%20Types%20on%20Collections&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2019%2F07%2F26%2Fstrong-types-on-collections%2F&#038;p&#091;images&#093;&#091;0&#093;=&#038;p&#091;title&#093;=Strong%20Types%20on%20Collections" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2019%2F07%2F26%2Fstrong-types-on-collections%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2019%2F07%2F26%2Fstrong-types-on-collections%2F&#038;title=Strong%20Types%20on%20Collections" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2019/07/26/strong-types-on-collections/">Strong Types on Collections</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4000</post-id>	</item>
		<item>
		<title>Getting the Benefits of Strong Typing in C++ at a Fraction of the Cost</title>
		<link>https://www.fluentcpp.com/2018/04/06/strong-types-by-struct/</link>
					<comments>https://www.fluentcpp.com/2018/04/06/strong-types-by-struct/#comments</comments>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Fri, 06 Apr 2018 01:00:30 +0000</pubDate>
				<category><![CDATA[Strong types]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[compilation time]]></category>
		<category><![CDATA[expressive]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[simple]]></category>
		<category><![CDATA[strong types]]></category>
		<category><![CDATA[struct]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=3411</guid>

					<description><![CDATA[<p>Guest writer Vincent Zalzal talks to us about lightweight strong types. Vincent is a software developer working in the computer vision industry for the last 12 years. He appreciates all the levels of complexity involved in software development, from how to optimize memory cache accesses to devising algorithms and heuristics to solve complex applications, all [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2018/04/06/strong-types-by-struct/">Getting the Benefits of Strong Typing in C++ at a Fraction of the Cost</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><em><img loading="lazy" decoding="async" class="alignright wp-image-3416" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/penrose_vz5.png?resize=220%2C220&#038;ssl=1" alt="strong types struct" width="220" height="220" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/penrose_vz5.png?resize=300%2C300&amp;ssl=1 300w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/penrose_vz5.png?resize=150%2C150&amp;ssl=1 150w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/penrose_vz5.png?resize=32%2C32&amp;ssl=1 32w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/penrose_vz5.png?resize=100%2C100&amp;ssl=1 100w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/penrose_vz5.png?resize=201%2C201&amp;ssl=1 201w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/penrose_vz5.png?resize=400%2C400&amp;ssl=1 400w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/penrose_vz5.png?resize=440%2C440&amp;ssl=1 440w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/penrose_vz5.png?resize=540%2C540&amp;ssl=1 540w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/penrose_vz5.png?w=600&amp;ssl=1 600w" sizes="(max-width: 220px) 100vw, 220px" data-recalc-dims="1" />Guest writer Vincent Zalzal talks to us about lightweight strong types. Vincent is a software developer working in the computer vision industry for the last 12 years. He appreciates all the levels of complexity involved in software development, from how to optimize memory cache accesses to devising algorithms and heuristics to solve complex applications, all the way to developing stable and user-friendly frameworks. You can find him online on <a href="https://twitter.com/Vincent4096">Twitter</a> or <a href="https://www.linkedin.com/in/vincentzalzal/">LinkedIn</a>.</em></p>
<p>Strong types promote safer and more expressive code. I won&#8217;t repeat what Jonathan has presented already in his <a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/">series on strong types</a>.</p>
<p>I suspect some people may find that the <code><a href="https://github.com/joboccara/NamedType">NamedType</a></code> class template has a nice interface but is using a somewhat heavy machinery to achieve the modest goal of strong typing. For those people, I have good news: you can achieve many of the functionalities of <code>NamedType</code>, with a very simple tool. That tool is the humble struct.</p>
<h3><span style="color: #ff6600;">Struct as strong type</span></h3>
<p>Let&#8217;s look at a simplified version of <code>NamedType</code>, without Skills:</p>
<pre class="lang:c++ decode:true ">template &lt;typename T, typename Parameter&gt;
class NamedType
{
public:
    explicit NamedType(T const&amp; value) : value_(value) {}

    template&lt;typename T_ = T, typename = IsNotReference&lt;T_&gt;&gt;
    explicit NamedType(T&amp;&amp; value) : value_(std::move(value)) {}

    T&amp; get() { return value_; }
    T const&amp; get() const {return value_; }

private:
    T value_;
};</pre>
<p>This class is hiding the underlying value, and giving access to it with <code>get()</code>. There seems to be no <code>set()</code> method, but it is still there, hidden in the <code>get()</code> function. Indeed, since the <code>get()</code> function returns a non-const reference, we can do:</p>
<pre class="lang:c++ decode:true ">using Width = NamedType&lt;double, struct WidthTag&gt;;
Width width(42);
width.get() = 1337;</pre>
<p>Since the <code>get()</code> method is not enforcing any invariant and the underlying value is accessible, it is essentially public. Let&#8217;s make it public then! By doing so, we get rid of the <code>get()</code> functions. Also, since everything in the class is public, and since, semantically, it is not enforcing any invariant, let&#8217;s use a struct instead:</p>
<pre class="lang:c++ decode:true">template &lt;typename T, typename Parameter&gt;
struct NamedType
{
    explicit NamedType(T const&amp; value) : value_(value) {}

    template&lt;typename T_ = T, typename = IsNotReference&lt;T_&gt;&gt;
    explicit NamedType(T&amp;&amp; value) : value_(std::move(value)) {}

    T value_;
};</pre>
<p>But wait: do we really need those explicit constructors? If we remove them, we can use <a href="http://en.cppreference.com/w/cpp/language/aggregate_initialization" target="_blank" rel="noopener">aggregate initialization</a>, which performs exactly the same thing. We end up with:</p>
<pre class="lang:c++ decode:true ">template &lt;typename T, typename Parameter&gt;
struct NamedType
{
    T value_;
};</pre>
<p>That struct is not reusing code anymore. So the last simplification is to use a non-template struct directly to define the strong type.</p>
<pre class="lang:c++ decode:true ">struct Width { double v; };</pre>
<p>There you have it: a strong type, without heavy machinery. Want to see it in action?</p>
<pre class="lang:c++ decode:true ">struct Width { double v; };
struct Height { double v; };

class Rectangle { /* ... */ };
Rectangle make_rect(Width width, Height height) { return Rectangle(/* ... */); }
Rectangle make_square(Width width) { return Rectangle(/* ... */); }

void foo()
{
    // Aggregate initialization copies lvalues and moves rvalues.
    Width width {42.0};

    // constexpr also works.
    constexpr Width piWidth {3.1416};

    // get() and set() are free.
    // set() copies lvalues and moves rvalues.
    double d = width.v;
    width.v = 1337.0;

    // Copy and move constructors are free.
    Width w1 {width};
    Width w2 {std::move(w1)};

    // Copy and move assignment operators are free.
    w1 = width;
    w2 = std::move(w1);

    // Call site is expressive and type-safe.
    auto rect = make_rect(Width{1.618}, Height{1.0});
    // make_rect(Height{1.0}, Width{1.618}); does not compile

    // Implicit conversions are disabled by default.
    // make_rect(1.618, 1.0); does not compile
    // double d1 = w1; does not compile

    // Call site can also be terse, if desired (not as type-safe though).
    auto square = make_square( {2.718} );
}</pre>
<p>This code looks a lot like the one you would get using <code>NamedType</code> (except for the last line that would be prevented by the explicit constructor). Here are some added benefits of using structs as strong types:</p>
<ul>
<li>more readable stack traces (<code>NamedType</code> can generate pretty verbose names)</li>
<li>code easier to understand for novice C++ developers and thus easier to adopt in a company</li>
<li>one fewer external dependency</li>
</ul>
<p>I like the convention of using <code>v</code> for the underlying value, because it mimics what the standard uses for variable templates, like <code>std::is_arithmetic_v</code> or <code>std::is_const_v</code>. Naturally, you can use whatever you find best, like <code>val</code> or <code>value</code>. Another nice convention is to use the underlying type as name:</p>
<pre class="lang:c++ decode:true ">struct Width { double asDouble; };

void foo()
{
    Width width {42};
    auto d = width.asDouble;
}

</pre>
<h3><span style="color: #ff6600;">Skills</span></h3>
<p>Using the struct as presented above requires accessing the underlying member directly. Often, few operations on the struct are necessary, and direct access to the underlying member can be hidden in member functions of the class using the strong type. However, in other cases where arithmetic operations are necessary, for example, in the case of a width, then skills are needed to avoid having to implement operators again and again.</p>
<p>The inheritance approach used by <code>NamedType</code> or <a href="http://www.boost.org/doc/libs/1_66_0/libs/utility/operators.htm">boost::operators</a> works well. I do not claim that the method I will present here is elegant, but it is an alternative to using inheritance that has advantages, notably simplicity.</p>
<h4><span style="color: #ff6600;">Operator Overloading</span></h4>
<p>First, note that almost all operators in C++ can be implemented as non-member functions. Here are the operators that cannot be implemented as non-member functions:</p>
<ul>
<li>assignment, i.e. <code>operator=</code> (in our case, the implicitly-generated version is okay)</li>
<li>function call, i.e. <code>operator()</code></li>
<li>subscripting, i.e. <code>operator[]</code></li>
<li>class member access, i.e. <code>operator-&gt;</code></li>
<li>conversion functions, e.g. <code>operator int()</code></li>
<li>allocation and deallocation functions (<code>new</code>, <code>new[]</code>, <code>delete</code>, <code>delete[]</code>)</li>
</ul>
<p>All other overloadable operators can be implemented as non-member functions. As a refresher, here they are:<br />
&#8211; unary: <code>+</code> <code>-</code> <code>*</code> <code>&amp;</code>  <code>~</code>  <code>!</code>  <code>++</code> (pre and post) <code>--</code> (pre and post)<br />
&#8211; binary: <code>+ - * / % ^ &amp; | &lt; &gt; += -= *= /= %= ^= &amp;= |= &lt;&lt; &gt;&gt; &gt;&gt;= &lt;&lt;= == != &lt;= &gt;= &amp;&amp; || , -&gt;*</code></p>
<p>As an example, for the <code>Width</code> type above, the less-than operator would look like this:</p>
<pre class="lang:c++ decode:true ">inline bool operator&lt;(Width lhs, Width rhs)
{
    return lhs.v &lt; rhs.v;
}</pre>
<p>As a side note, I chose to pass the widths by value in the code above for performance reasons. Given their small size, those structs are typically passed in directly in registers, like arithmetic types. The optimizer will also optimize the copy away since it is working mostly on arithmetic types here. Finally, for binary operations, further optimizations are sometimes possible because the compiler knows for certain there is no aliasing, i.e. the two operands do not share the same memory. For bigger structs (my personal threshold is more than 8 bytes) or structs with non-trivial constructors, I would pass the parameters by const lvalue reference.</p>
<p>All other relational operators would have to be defined similarly. To avoid repeating that code over and over again for each strong type, we must find a way to <strong>generate</strong> that code.</p>
<h4><span style="color: #ff6600;">The Inheritance Approach</span></h4>
<p><code>NamedType</code> uses inheritance and CRTP as code generator. It has the advantage of being part of the language. However, it pollutes the type name, especially when looking at a call stack. For example, the function:</p>
<pre class="lang:c++ decode:true ">using NT_Int32 = fluent::NamedType&lt;int32_t, struct Int32, fluent::Addable&gt;;
void vectorAddNT(NT_Int32* dst, const NT_Int32* src1, const NT_Int32* src2, int N);</pre>
<p>results in the following line in the call stack:</p>
<pre class="lang:c++ decode:true">vectorAddNT(fluent::NamedType&lt;int,Int32,fluent::Addable&gt; * dst, const fluent::NamedType&lt;int,Int32,fluent::Addable&gt; * src1, const fluent::NamedType&lt;int,Int32,fluent::Addable&gt; * src2, int N)</pre>
<p>This is for one skill; the problem gets worse the more skills are added.</p>
<h4><span style="color: #ff6600;">The Preprocessor Approach</span></h4>
<p>The oldest code generator would be the preprocessor. Macros could be used to generate the operator code. But code in macros is rarely a good option, because macros can&#8217;t be stepped into while debugging.</p>
<p>Another way to use the preprocessor as code generator is to use <strong>include files</strong>. Breakpoints can be set in included files without problem, and they can be stepped into. Unfortunately, to pass parameters to the code generator, we must resort to using define directives, but it is a small price to pay.</p>
<pre class="lang:c++ decode:true ">struct Width { double v; };

#define UTIL_OP_TYPE_T_ Width
#include &lt;util/operators/less_than_comparable.hxx&gt;
#undef UTIL_OP_TYPE_T_</pre>
<p>The file <code>less_than_comparable.hxx</code> would look like this:</p>
<pre class="lang:c++ decode:true ">inline bool operator&lt;(UTIL_OP_TYPE_T_ lhs, UTIL_OP_TYPE_T_ rhs)
{
    return lhs.v &lt; rhs.v;
}
inline bool operator&gt;(UTIL_OP_TYPE_T_ lhs, UTIL_OP_TYPE_T_ rhs)
{
    return lhs.v &gt; rhs.v;
}
// ...</pre>
<p>It is a good idea to use a different extension than usual for files included in this way. These are not normal headers; for example, header guards must absolutely not be used in them. The extension <code>.hxx</code> is less frequently used, but it is recognized as C++ code by most editors, so it can be a good choice.</p>
<p>To support other operators, you simply include multiple files. It is possible (and desirable) to create a hierarchy of operators, as is done in <code>boost::operators</code> (where the name <code>less_than_comparable</code> comes from). For example, the skills addable and subtractable could be grouped under the name <code>additive</code>.</p>
<pre class="lang:c++ decode:true ">struct Width { double v; };

#define UTIL_OP_TYPE_T_ Width
#include &lt;util/operators/additive.hxx&gt;
#include &lt;util/operators/less_than_comparable.hxx&gt;
// ...
#undef UTIL_OP_TYPE_T_

// util/operators/additive.hxx

#include &lt;util/operators/addable.hxx&gt;
#include &lt;util/operators/subtractable.hxx&gt;

// util/operators/addable.hxx

inline UTIL_OP_TYPE_T_ operator+(UTIL_OP_TYPE_T_ lhs, UTIL_OP_TYPE_T_ rhs)
{
    return {lhs.v + rhs.v};
}
inline UTIL_OP_TYPE_T_&amp; operator+=(UTIL_OP_TYPE_T_&amp; lhs, UTIL_OP_TYPE_T_ rhs)
{
    lhs.v += rhs.v;
    return lhs;
}

// etc</pre>
<p>It may come as a surprise that <code>operator+=</code> can be implemented as a non-member function. I think it highlights the fact that the struct is seen as data, not as object. It has no member function in itself. However, as mentioned above, there are a few operators that cannot be implemented as non-member functions, notably, <code>operator-&gt;</code>.</p>
<p>I would argue that if you need to overload those operators, the strong type is not semantically a struct anymore, and you would be better off using <code>NamedType</code>.</p>
<p>However, nothing prevents you from including files inside the struct definition, even if a few people may cringe when seeing this:</p>
<pre class="lang:c++ decode:true ">#define UTIL_OP_TYPE_T_ WidgetPtr
struct WidgetPtr
{
    std::unique_ptr&lt;Widget&gt; v;
    #include &lt;util/operators/dereferenceable.hxx&gt;
};
#undef UTIL_OP_TYPE_T_</pre>
<h4><span style="color: #ff6600;">The Code Generator Approach</span></h4>
<p>Big companies like Google rely more and more on bots to generate code (see <a href="https://developers.google.com/protocol-buffers/docs/reference/cpp-generated">protobuf</a>) and commits (see <a href="https://youtu.be/W71BTkUbdqE" target="_blank" rel="noopener">this presentation</a>). The obvious drawback of the method is that you need an external tool (like <a href="https://nedbatchelder.com/code/cog/">Cog</a> for example) integrated into the build system to generate the code. However, once the code is generated, it is very straightforward to read and use (and also to analyze and compile). Since each strong type has its own generated copy, it is also easier to set a breakpoint in a function for a specific type.</p>
<p>Using a tool to generate code can lead to an elegant pseudo-language of keywords added to the language. This is the approach taken by Qt, and they defend it well (see <a href="http://doc.qt.io/qt-5/why-moc.html">Why Does Qt Use Moc for Signals and Slots?</a>)</p>
<h4><span style="color: #ff6600;">Skills for enums</span></h4>
<p>Skills can also be useful on enums to implement bit flags. As a side note, the inheritance approach cannot be applied to enums, since they can’t inherit functionality. However, strategies based on non-member functions can be used in that case. Bit flags are an interesting use-case that deserve an article of their own.</p>
<h3><span style="color: #ff6600;">Performance</span></h3>
<p>As Jonathan already stated, <a href="https://www.fluentcpp.com/2017/05/05/news-strong-types-are-free/"><code>NamedType</code> is a zero-cost abstraction</a>: given a sufficient level of optimisation (typically O1 or O2), compilers emit the same code as if arithmetic types were used directly. This also holds for using a struct as strong type. However, I wanted to test if compilers were also able to vectorize the code correctly when using <code>NamedType</code> or a struct instead of arithmetic types.</p>
<p>I compiled the following code on Visual Studio 2017 (version 15.5.7) with default release options in both 32-bit and 64-bit configurations. I used <a href="https://godbolt.org/">godbolt</a> to test GCC 7.3 and Clang 5.0 in 64-bit, using the -O3 optimization flag.</p>
<pre class="lang:c++ decode:true ">using NT_Int32 = fluent::NamedType&lt;int32_t, struct Int32, fluent::Addable&gt;;

struct S_Int32 { int32_t v; };

S_Int32 operator+(S_Int32 lhs, S_Int32 rhs)
{
    return { lhs.v + rhs.v };
}

void vectorAddNT(NT_Int32* dst, const NT_Int32* src1, const NT_Int32* src2, int N)
{
    for (int i = 0; i &lt; N; ++i)
        dst[i] = src1[i] + src2[i];
}

void vectorAddS(S_Int32* dst, const S_Int32* src1, const S_Int32* src2, int N)
{
    for (int i = 0; i &lt; N; ++i)
        dst[i] = src1[i] + src2[i];
}

void vectorAddi32(int32_t* dst, const int32_t* src1, const int32_t* src2, int N)
{
    for (int i = 0; i &lt; N; ++i)
        dst[i] = src1[i] + src2[i];
}</pre>
<p>Under Clang and GCC, all is well: the generated code is the same for all three functions, and SSE2 instructions are used to load, add and store the integers.</p>
<p>Unfortunately, results under VS2017 are less than stellar. Whereas the generated code for arithmetic types and structs both use SSE2 instructions, <code>NamedType</code> seems to inhibit vectorization. The same behavior can be observed if <code>get()</code> is used directly instead of using the <code>Addable</code> skill. This is something to keep in mind when using <code>NamedType</code> with big arrays of data.</p>
<p>VS2017 also disappoints in an unexpected way. The size of <code>NT_Int32</code> is 4 bytes on all platforms, with all compilers, as it should be. However, as soon as a second skill is added to the <code>NamedType</code>, for example <code>Subtractable</code>, the size of the type becomes 8 bytes! This is also true for other arithmetic types. Replacing <code>int32_t</code> in the <code>NamedType</code> alias with double yields a size of 8 bytes for one skill, but 16 bytes as soon as a second skill is added.</p>
<p>Is it a missing empty base class optimization in VS2017? Such a pessimization yields memory-inefficient, cache-unfriendly code. Let’s hope future versions of VS2017 will fare better.</p>
<p>EDIT: As redditer fernzeit <a href="https://www.reddit.com/r/cpp/comments/8a7so6/getting_the_benefits_of_strong_typing_in_c_at_a/dx7e1qn/" target="_blank" rel="noopener" data-saferedirecturl="https://www.google.com/url?hl=fr&amp;q=https://www.reddit.com/r/cpp/comments/8a7so6/getting_the_benefits_of_strong_typing_in_c_at_a/dx7e1qn/&amp;source=gmail&amp;ust=1524721025008000&amp;usg=AFQjCNGlyasAaUOQZ6tI87wE0EQKs_kyGQ">pointed out</a>, the empty base class optimization is <a href="https://blogs.msdn.microsoft.com/vcblog/2016/03/30/optimizing-the-layout-of-empty-base-classes-in-vs2015-update-2-3/" target="_blank" rel="noopener" data-saferedirecturl="https://www.google.com/url?hl=fr&amp;q=https://blogs.msdn.microsoft.com/vcblog/2016/03/30/optimizing-the-layout-of-empty-base-classes-in-vs2015-update-2-3/&amp;source=gmail&amp;ust=1524721025008000&amp;usg=AFQjCNGJcSSidC5GZXiLGilAuz199gR6nw">disabled by default</a> when using multiple inheritance on Visual Studio. When using the <span style="font-family: monospace;">__declspec(empty_bases)</span> attribute, Visual Studio generates the same class layout as Clang and GCC. The attribute has been <a href="https://github.com/joboccara/NamedType/commit/eec1ec63409b8a7741aea0003afd84d76d1faf0e" target="_blank" rel="noopener">added to the <code>NamedType</code></a> implementation to fix the issue.</p>
<h3><span style="color: #ff6600;">Compilation time</span></h3>
<p>A criticism often formulated against templates is that they tend to slow compilation down. Could it affect <code>NamedType</code>? On the other hand, since all the code for <code>NamedType</code> is considered external to a project, it can be added to a precompiled header, which means it will be read from disk and parsed only once.</p>
<p>Using a struct as strong type with include files for skills does not incur the template penalty, but requires reading from disk and parsing the skill files again and again. Precompiled headers cannot be used for the skill files, because they change each time they are included. However, the struct can be forward declared, a nice compilation firewall that <code>NamedType</code> cannot use, since type aliases cannot be forward declared.</p>
<p>To test compilation time, I created a project with 8 strong types, each contained in its own header file, and 8 simple algorithms, each using one strong type and having both a header file and an implementation file. A main file then includes all the algorithm headers, instantiates the strong types and call the functions one at a time.</p>
<p>Compilation time has been measured in Visual Studio 2017 (version 15.5.7) using the very useful <a href="http://mike-ward.net/vscoloroutput/">VSColorOutput</a> extension (check it out!). Default compilation options for a Windows console application were used. For every configuration, 5 consecutive compilations have been performed and the median time computed. Consequently, these are not “cold” times, caching affects the results.</p>
<p>Two scenarios have been considered: the full rebuild, typical of build machines, and the single-file incremental build, typical of the inner development loop.</p>
<p>32-bit and 64-bit configurations yielded no significant difference in compilation time, so the average of the two is reported below. This is also the case for debug and release configurations (unless otherwise stated). All times are in seconds, with a variability of about ± 0.1s.</p>
<div id="attachment_3414" style="width: 444px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-3414" class="wp-image-3414 size-full" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table1.png?resize=434%2C187&#038;ssl=1" alt="struct strong type C++" width="434" height="187" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table1.png?w=434&amp;ssl=1 434w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table1.png?resize=150%2C65&amp;ssl=1 150w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table1.png?resize=300%2C129&amp;ssl=1 300w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table1.png?resize=32%2C14&amp;ssl=1 32w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table1.png?resize=232%2C100&amp;ssl=1 232w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table1.png?resize=201%2C87&amp;ssl=1 201w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table1.png?resize=350%2C151&amp;ssl=1 350w" sizes="(max-width: 434px) 100vw, 434px" data-recalc-dims="1" /><p id="caption-attachment-3414" class="wp-caption-text">Table 1: Compilation time, in seconds, of different strong typing strategies, without precompiled headers.</p></div>
<p>A first look at the results in Table 1 could lead to hasty conclusions. <code>NamedType</code> appears slower, but its compilation time can be greatly reduced with the use of precompiled headers. Also, the other strategies have an unfair advantage: they don’t include any standard headers. NamedType includes four of them: <code>type_traits</code>, <code>functional</code>, <code>memory</code> and <code>iostream</code> (mostly to implement the various skills). In most real-life projects, those headers would also be included, probably in precompiled headers to avoid slowing down compilation time.</p>
<p>Also it&#8217;s worth noting that <code>NamedType</code> currently brings in all skills in the same header. Presumably, including skill headers on demand could decrease compilation time in some applications.</p>
<p>To get a fairer picture, precompiled headers have been used to generate the results in Table 2 below:</p>
<div id="attachment_3415" style="width: 444px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-3415" class="wp-image-3415 size-full" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table2.png?resize=434%2C187&#038;ssl=1" alt="struct strong type C++" width="434" height="187" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table2.png?w=434&amp;ssl=1 434w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table2.png?resize=150%2C65&amp;ssl=1 150w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table2.png?resize=300%2C129&amp;ssl=1 300w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table2.png?resize=32%2C14&amp;ssl=1 32w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table2.png?resize=232%2C100&amp;ssl=1 232w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table2.png?resize=201%2C87&amp;ssl=1 201w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/03/struct_strong_type_table2.png?resize=350%2C151&amp;ssl=1 350w" sizes="(max-width: 434px) 100vw, 434px" data-recalc-dims="1" /><p id="caption-attachment-3415" class="wp-caption-text">Table 2: Compilation time, in seconds, of different strong typing strategies, with precompiled headers.</p></div>
<p>Ah, much nicer! It is hazardous to extrapolate these results to bigger, real-life projects, but they are encouraging and support the idea that strong typing is a zero-cost abstraction, with negligible impact on compilation time.</p>
<h3><span style="color: #ff6600;">Conclusion</span></h3>
<p>My goal is <strong>not</strong> to convince you that using structs as strong types is better than using <code>NamedType</code>. Rather, strong typing is so useful that you should have <strong>alternatives</strong> if <code>NamedType</code> doesn’t suit you for some reason, while we wait for an <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0109r0.pdf">opaque typedef</a> to be part of the C++ standard.</p>
<p>One alternative that is easy to adopt is to <strong>use structs as strong types</strong>. It offers most of <code>NamedType</code> functionality and type safety, while being easier to understand for novice C++ programmers — and some compilers.</p>
<p>If you have questions or comments, I would enjoy reading them! Post them below, or contact me on <a href="https://twitter.com/Vincent4096">Twitter</a>.</p>
<p>Related articles:</p>
<ul>
<li><a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/">Strong types for strong interfaces</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/05/news-strong-types-are-free/">Good news: strong types are (mostly) free in C++</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F04%2F06%2Fstrong-types-by-struct%2F&#038;t=Getting%20the%20Benefits%20of%20Strong%20Typing%20in%20C%2B%2B%20at%20a%20Fraction%20of%20the%20Cost&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F04%2F06%2Fstrong-types-by-struct%2F&#038;p&#091;images&#093;&#091;0&#093;=https%3A%2F%2Fwww.fluentcpp.com%2Fwp-content%2Fuploads%2F2018%2F03%2Fpenrose_vz5-300x300.png&#038;p&#091;title&#093;=Getting%20the%20Benefits%20of%20Strong%20Typing%20in%20C%2B%2B%20at%20a%20Fraction%20of%20the%20Cost" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F04%2F06%2Fstrong-types-by-struct%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F04%2F06%2Fstrong-types-by-struct%2F&#038;title=Getting%20the%20Benefits%20of%20Strong%20Typing%20in%20C%2B%2B%20at%20a%20Fraction%20of%20the%20Cost" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2018/04/06/strong-types-by-struct/">Getting the Benefits of Strong Typing in C++ at a Fraction of the Cost</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.fluentcpp.com/2018/04/06/strong-types-by-struct/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3411</post-id>	</item>
		<item>
		<title>Strong Types For Strong Interfaces: my talk at Meeting C++</title>
		<link>https://www.fluentcpp.com/2018/02/02/strong-types-strong-interfaces-talk-meeting-cpp/</link>
					<comments>https://www.fluentcpp.com/2018/02/02/strong-types-strong-interfaces-talk-meeting-cpp/#comments</comments>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Fri, 02 Feb 2018 01:00:26 +0000</pubDate>
				<category><![CDATA[Strong types]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=3009</guid>

					<description><![CDATA[<p>A couple of weeks ago I had the opportunity to speak at Meeting C++, in Berlin. This talk has come out on Youtube recently, and I&#8217;d like to share it with you. This presentation sums up the fundamental aspects of strong typing in C++ as I see it. I hope you enjoy it! Of course, [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2018/02/02/strong-types-strong-interfaces-talk-meeting-cpp/">Strong Types For Strong Interfaces: my talk at Meeting C++</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>A couple of weeks ago I had the opportunity to speak at Meeting C++, in Berlin. This talk has come out on Youtube recently, and I&#8217;d like to share it with you.</p>
<p>This presentation sums up the fundamental aspects of strong typing in C++ as I see it. I hope you enjoy it! Of course, any feedback is welcome.</p>
<p>If you want to read about more advanced or exploratory aspects of strong typing, you can also have a look at the <strong>Strong types</strong> section of the <a href="http://fluentcpp.com/posts">contents of Fluent C++</a>.</p>
<p><iframe loading="lazy" width="560" height="315" src="https://www.youtube.com/embed/WVleZqzTw2k" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen="allowfullscreen"></iframe></p>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F02%2F02%2Fstrong-types-strong-interfaces-talk-meeting-cpp%2F&#038;t=Strong%20Types%20For%20Strong%20Interfaces%3A%20my%20talk%20at%20Meeting%20C%2B%2B&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F02%2F02%2Fstrong-types-strong-interfaces-talk-meeting-cpp%2F&#038;p&#091;images&#093;&#091;0&#093;=https%3A%2F%2Fi0.wp.com%2Fwww.fluentcpp.com%2Fwp-content%2Fuploads%2F2018%2F01%2Fstrong_types_featured.jpg%3Ffit%3D800%252C450%26ssl%3D1&#038;p&#091;title&#093;=Strong%20Types%20For%20Strong%20Interfaces%3A%20my%20talk%20at%20Meeting%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F02%2F02%2Fstrong-types-strong-interfaces-talk-meeting-cpp%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F02%2F02%2Fstrong-types-strong-interfaces-talk-meeting-cpp%2F&#038;title=Strong%20Types%20For%20Strong%20Interfaces%3A%20my%20talk%20at%20Meeting%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2018/02/02/strong-types-strong-interfaces-talk-meeting-cpp/">Strong Types For Strong Interfaces: my talk at Meeting C++</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.fluentcpp.com/2018/02/02/strong-types-strong-interfaces-talk-meeting-cpp/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3009</post-id>	</item>
		<item>
		<title>How to Be Clear About What Your Functions Return</title>
		<link>https://www.fluentcpp.com/2018/01/23/function-return/</link>
					<comments>https://www.fluentcpp.com/2018/01/23/function-return/#comments</comments>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Tue, 23 Jan 2018 01:00:13 +0000</pubDate>
				<category><![CDATA[Strong types]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[expressive]]></category>
		<category><![CDATA[fail]]></category>
		<category><![CDATA[fluent]]></category>
		<category><![CDATA[interface]]></category>
		<category><![CDATA[return]]></category>
		<category><![CDATA[strong types]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=2524</guid>

					<description><![CDATA[<p>What&#8217;s in a function&#8217;s interface? In most languages, a function&#8217;s interface has 3 main parts: the function&#8217;s name: it indicates what the function does, the function&#8217;s parameters: they show what the function takes as input to do its job, the function&#8217;s return type: it indicates the output of the function. ReturnType functionName(ParameterType1 parameterName1, ParameterType2 parameterName2); [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2018/01/23/function-return/">How to Be Clear About What Your Functions Return</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><span style="color: #000000;">What&#8217;s in a function&#8217;s interface?</span></p>
<p>In most languages, a function&#8217;s interface has 3 main parts:</p>
<ul>
<li>the function&#8217;s name: it indicates what the function does,</li>
<li>the function&#8217;s parameters: they show what the function takes as input to do its job,</li>
<li>the function&#8217;s return type: it indicates the output of the function.</li>
</ul>
<pre class="lang:c++ decode:true">ReturnType functionName(ParameterType1 parameterName1, ParameterType2 parameterName2);</pre>
<p>So far, so good.</p>
<p>But when looking at this prototype, we can notice that something isn&#8217;t symmetric: the function&#8217;s parameters have both a type and a name, while the returned value only has a type. Indeed, <strong>the return value doesn&#8217;t have a name</strong>.</p>
<p>In a function declaration, one could choose to also omit the names of the parameters. But still, the return type doesn&#8217;t have a choice. It can only be&#8230; a type.</p>
<p>Why is that? My take is that it&#8217;s because we expect the the function&#8217;s name to be clear enough to express what it returns, plus the returned value has a visible type. So a name for the returned value itself would be superfluous.</p>
<p>But is this the case 100% of the time?</p>
<h3><span style="color: #ff6600;">A use case that should not exist, but that does</span></h3>
<p>No. In theory it works fine but, realistically, it&#8217;s not always the case that a function&#8217;s name informs you exactly of what to expect as a return value.</p>
<p>Let&#8217;s take the example of a function that performs a side effect, like saving a piece of information in a database:</p>
<pre class="lang:c++ decode:true">void save(PieceOfData const&amp; preciousData);</pre>
<p>And say that this operation could potentially fail. How does the function lets it caller know whether or not the operation succeeded?</p>
<p>One way to go about that is to make the <code>save</code> function throw an exception. It works, but not everyone uses exceptions (exceptions need exception-safe code surrounding them, they may impact performance, some teams ban them from their coding conventions&#8230;). There have been <a href="https://blog.tartanllama.xyz/optional-expected/" target="_blank" rel="noopener">hot debates and suggested alternatives</a> about this.</p>
<p>We already come across a clear way to indicate that a function could potentially fail to return its result: <a href="https://www.fluentcpp.com/2016/11/24/clearer-interfaces-with-optionalt/">using optionals</a>. That is to say, return an <code>optional&lt;T&gt;</code>, conveying the message that we expect to return a <code>T</code>, but this could potentially fail, and the function caller is supposed to check whether that returned <code>optional</code> is full or empty.</p>
<p>But here we&#8217;re talking about a function that returns <strong>nothing</strong>. It merely saves  piece of data in a database. Should it return an <code>optional&lt;void&gt;</code> then? This would read that it is supposed to return <code>void</code> but it may return something that isn&#8217;t really a <code>void</code>, but an empty box instead. An empty void. Weird. And <code>std::optional&lt;void&gt;</code> doesn&#8217;t compile anyway!</p>
<p>Another possibility is to return a boolean indicating whether or not the function succeeded:</p>
<pre class="lang:c++ decode:true">bool save(PieceOfData const&amp; preciousData);</pre>
<p>But this is less than ideal. First, the returned value could be ignored at call site. Though this could be prevented by adding the  <code>[[nodiscard]]</code> attribute in C++17:</p>
<pre class="lang:c++ decode:true">[[nodiscard]] bool save(PieceOfData const&amp; preciousData);</pre>
<p>Second, just by looking at the function&#8217;s prototype, we don&#8217;t know if that <code>bool</code> means success or failure. Or something else totally unrelated, for that matter. We could look it up in the documentation of the function, but it takes more time and introduces a risk of getting it wrong anyway.</p>
<p>Since the function is only called &#8220;<code>save</code>&#8220;, its name doesn&#8217;t say what the return type represents. We could call it something like <code>saveAndReturnsIfSuceeded</code> but&#8230; we don&#8217;t really want to see that sort of name in code, do we?</p>
<h4><span style="color: #ff6600;">Meta information</span></h4>
<p>It is interesting to realize that this is a more general use case that just failure or success. Indeed, sometimes the only way to retrieve a piece of information about a certain operation is to actually perform it.</p>
<p>For instance, say we have a function that takes an <code>Input</code> and uses it to add and to remove entries from a existing <code>Entries</code> collection:</p>
<pre class="lang:c++ decode:true">void updateEntries(Input const&amp; input, Entries&amp; entries);</pre>
<p>And we&#8217;d like to retrieve some data about this operation. Say an <code>int</code> that represents the number of entries removed, for example. We could make the function output that <code>int</code> via its return type:</p>
<pre class="lang:c++ decode:true">int updateEntries(Input const&amp; input, Entries&amp; entries);</pre>
<p>But the return type doesn&#8217;t tell what it represents here, only that it&#8217;s implemented as an <code>int</code>. We&#8217;ve lost information here.</p>
<p>In this particular case, we could have added an <code>int&amp; entriesRemoved</code> function parameter, but I don&#8217;t like this pattern because it forces the caller to initialize a variable before calling the functions, which doesn&#8217;t work for all types, and <a href="https://www.fluentcpp.com/2017/12/08/make-functions-functional-video/" target="_blank" rel="noopener">a non-const reference means input-output</a> and not output, so it&#8217;s not exactly the message we&#8217;d like to convey here.</p>
<p>What to do then?</p>
<h3><span style="color: #ff6600;">Named return types: strong return types?</span></h3>
<p>So in summary, we have return types that lack a meaningful name. This sounds like a job for <a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/">strong types</a>: indeed, strong types help put meaningful names over types!</p>
<p><em>Spoiler alert: strong types won&#8217;t be the option that we&#8217;ll retain for most cases of return types in the end. Read on to see why and what to use instead.</em></p>
<p>Let&#8217;s use <code><a href="https://github.com/joboccara/NamedType" target="_blank" rel="noopener">NamedType</a></code> as an implementation of strong types, and create return types with a name that make sense in each of our functions&#8217; contexts.</p>
<p>So our <code>save</code> function returns a <code>bool</code> that is <code>true</code> if the operation was a success. Let&#8217;s stick a name over that <code>bool</code>:</p>
<pre class="lang:c++ decode:true">using HasSucceeded = NamedType&lt;bool, struct HasSucceededTag&gt;;</pre>
<p>The second parameter of <code>NamedType</code> is a &#8220;phantom type&#8221;, that is to say that it&#8217;s there only for differentiating <code>HasSucceeded</code> from another <code>NamedType</code> over a <code>bool</code>.</p>
<p>Let&#8217;s use <code>HasSucceeded</code> in our function&#8217;s interface:</p>
<pre class="lang:c++ decode:true">HasSucceeded save(PieceOfData const&amp; preciousData);</pre>
<p>The function now expresses that it returns the information about whether the operation succeeded or not.</p>
<p>The implementation of the function would build a <code>HasSucceeded</code> and return it:</p>
<pre class="lang:c++ decode:true ">HasSucceeded save(PieceOfData const&amp; preciousData)
{
    // attempt to save...
    // if it failed
    return HasSucceeded(false);
    // else, if all goes well
    return HasSucceeded(true);
}</pre>
<p>And at call site:</p>
<pre class="lang:c++ decode:true">HasSucceeded hasSucceeded = save(myData); // or auto hasSucceeded = ...

if(!hasSucceeded.get())
{
    // deal with failure...</pre>
<p>Note that we can choose to get rid of the call to <code>.get()</code> by making <code>HasSucceeded</code> use the <a href="https://www.fluentcpp.com/2017/11/07/calling-functions-methods-strong-types/"><code>FunctionCallable</code></a> skill.</p>
<p>For the sake of the example, let&#8217;s apply the same technique to our <code>updateEntries</code> function:</p>
<pre class="lang:c++ decode:true ">using NumberOfEntriesRemoved = NamedType&lt;int, struct NumberOfEntriesRemovedTag&gt;;

NumberOfEntriesRemoved updateEntries(Input const&amp; input, Entries&amp; entries);</pre>
<p>By looking at the interface, we now know that it outputs the number of entries removed via the return type.</p>
<h3><span style="color: #ff6600;">Just a weak type will do here</span></h3>
<p>The above works, but it&#8217;s needlessly sophisticated. In this case, the only thing we need is a name for other human beings to understand the interface. We don&#8217;t need to create a specific type used only in the context of the return type to also let the compiler know what we mean by it.</p>
<p>Why is that? Contrast our example with the case of input parameters of a function:</p>
<pre class="lang:c++ decode:true">void setPosition(int row, int column);

// Call site
setPosition(36, 42);</pre>
<p>Since there are several parameters that could be mixed up (and the program would still compile), introducing strong types such as <code>Row</code> and <code>Column</code> are useful to make sure we pass the parameters in the right order:</p>
<pre class="lang:c++ decode:true ">void setPosition(Row row, Column column);

// Call site:
setPosition(Row(36), Column(42));</pre>
<p>But in the return type, what is there to mix up? There is only one value returned anyway!</p>
<p>So a simple alias does the job just well:</p>
<pre class="lang:c++ decode:true ">using HasSucceeded = bool;
HasSucceeded save(PieceOfData const&amp; preciousData);</pre>
<p>This is the <strong>most adapted solution</strong> in this case, in my opinion.</p>
<h4><span style="color: #ff6600;">The case where strong types <em>are</em> useful in return types</span></h4>
<p>However there are at least two specific cases where strong types are helpful to clarify a returned value.</p>
<p>One is to <a href="https://www.fluentcpp.com/2017/11/10/strong-types-multiple-return-values/">use strong types to return multiple values</a>.</p>
<p>The other is when you already have a strong type that represents the return value, and that you <strong>already use</strong> at other places in the codeline. For instance, if you have a strong type <code>SerialNumber</code> that strengthen a <code>std::string</code>, and you use it at various places, it makes perfect sense to return it from a function.</p>
<p>The point I want to make is not to create a strong type for the sole purpose of returning it from a function and immediately retrieving the value inside it afterwards. Indeed, in this case <strong>a classical alias will do</strong>.</p>
<h3><span style="color: #ff6600;">What&#8217;s in a <em>expressive</em> function&#8217;s interface?</span></h3>
<p>This technique helps us be more explicit about what it is that a function is returning.</p>
<p>This is part of a more general objective, which is to leverage on every element of the function to express useful information:</p>
<ul>
<li>a clear function name: by using <a href="https://www.fluentcpp.com/2017/01/30/how-to-choose-good-names/">good naming</a>,</li>
<li>well-designed function parameters (a 3-post series coming soon),</li>
<li>an explicit output: either by returning the output directly (thus <a href="https://www.fluentcpp.com/2016/11/22/make-your-functions-functional/">making functions functional</a>), or by <a href="https://www.fluentcpp.com/2016/11/24/clearer-interfaces-with-optionalt/">using an optional</a> or, if it comes to that, returning something else, like we saw today. But always, by being the clearest possible about it.</li>
</ul>
<p>You may also like:</p>
<ul>
<li><a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/">Strong types for strong interfaces</a></li>
<li><a href="https://www.fluentcpp.com/2016/11/22/make-your-functions-functional/">Make your functions functional</a></li>
<li>The right question for the right name</li>
<li><a href="https://www.fluentcpp.com/2017/01/30/how-to-choose-good-names/">How to choose good names in code</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F23%2Ffunction-return%2F&#038;t=How%20to%20Be%20Clear%20About%20What%20Your%20Functions%20Return&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F23%2Ffunction-return%2F&#038;p&#091;images&#093;&#091;0&#093;=&#038;p&#091;title&#093;=How%20to%20Be%20Clear%20About%20What%20Your%20Functions%20Return" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F23%2Ffunction-return%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F23%2Ffunction-return%2F&#038;title=How%20to%20Be%20Clear%20About%20What%20Your%20Functions%20Return" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2018/01/23/function-return/">How to Be Clear About What Your Functions Return</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.fluentcpp.com/2018/01/23/function-return/feed/</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2524</post-id>	</item>
		<item>
		<title>Strong Optionals</title>
		<link>https://www.fluentcpp.com/2018/01/16/strong-optionals/</link>
					<comments>https://www.fluentcpp.com/2018/01/16/strong-optionals/#comments</comments>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Tue, 16 Jan 2018 01:00:47 +0000</pubDate>
				<category><![CDATA[Strong types]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[expressive]]></category>
		<category><![CDATA[interface]]></category>
		<category><![CDATA[strong optional]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=2583</guid>

					<description><![CDATA[<p>Both strong types and optionals are useful tools to make our interfaces more expressive. Could they be used in synergy to make one benefit from each other? The contents of this post are at an experimental stage. They are laid out here to expose a problem and a possible solution, and as a basis for [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2018/01/16/strong-optionals/">Strong Optionals</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-2935" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/strong_optionals2.png?resize=1280%2C720&#038;ssl=1" alt="Strong optionals" width="1280" height="720" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/strong_optionals2.png?w=1280&amp;ssl=1 1280w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/strong_optionals2.png?resize=150%2C84&amp;ssl=1 150w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/strong_optionals2.png?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/strong_optionals2.png?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/strong_optionals2.png?resize=1024%2C576&amp;ssl=1 1024w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/strong_optionals2.png?resize=32%2C18&amp;ssl=1 32w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/strong_optionals2.png?resize=178%2C100&amp;ssl=1 178w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/strong_optionals2.png?resize=201%2C113&amp;ssl=1 201w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/strong_optionals2.png?resize=350%2C197&amp;ssl=1 350w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/strong_optionals2.png?resize=711%2C400&amp;ssl=1 711w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/strong_optionals2.png?resize=782%2C440&amp;ssl=1 782w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/strong_optionals2.png?resize=960%2C540&amp;ssl=1 960w" sizes="(max-width: 1000px) 100vw, 1000px" data-recalc-dims="1" /></p>
<p>Both <a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/">strong types</a> and <a href="https://www.fluentcpp.com/2016/11/24/clearer-interfaces-with-optionalt/">optionals</a> are useful tools to make our interfaces more expressive. Could they be used in synergy to make one benefit from each other?</p>
<p>The contents of this post are at an experimental stage. They are laid out here to expose a problem and a possible solution, and as a basis for discussion. So your feedback will be welcome on this article (as it is welcome on any post, really).</p>
<h3><span style="color: #ff6600;">All optionals are grey in the dark</span></h3>
<p><img loading="lazy" decoding="async" class="alignright wp-image-2938 size-medium" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/cat-304156_640.png?resize=275%2C300&#038;ssl=1" alt="strong optional" width="275" height="300" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/cat-304156_640.png?resize=275%2C300&amp;ssl=1 275w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/cat-304156_640.png?resize=137%2C150&amp;ssl=1 137w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/cat-304156_640.png?resize=29%2C32&amp;ssl=1 29w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/cat-304156_640.png?resize=92%2C100&amp;ssl=1 92w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/cat-304156_640.png?resize=184%2C201&amp;ssl=1 184w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/cat-304156_640.png?resize=366%2C400&amp;ssl=1 366w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/cat-304156_640.png?resize=403%2C440&amp;ssl=1 403w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/cat-304156_640.png?resize=494%2C540&amp;ssl=1 494w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2018/01/cat-304156_640.png?w=586&amp;ssl=1 586w" sizes="(max-width: 275px) 100vw, 275px" data-recalc-dims="1" />Optional can be useful to execute <a href="https://www.fluentcpp.com/2016/12/01/partial-queries-with-optionalt/">partial queries</a>.</p>
<p>For instance, let&#8217;s consider this interface that retrieves a collection of <code>Employee</code>s that have a given first name and last name:</p>
<pre class="lang:c++ decode:true">std::vector&lt;Employees&gt; findEmployees(std::string const&amp; firstName, std::string const&amp; lastName);</pre>
<p>The following call:</p>
<pre class="lang:c++ decode:true">findEmployees("John", "Doe")</pre>
<p>returns the collection of the employees that are called John Doe.</p>
<p>Now say that we want to add a new functionality: searching all the employees that have a given first name, like &#8220;John&#8221;. Or a given last name, like &#8220;Doe&#8221;.</p>
<p>To achieve this, we can make this interface accept optionals instead of hard strings:</p>
<pre class="lang:c++ decode:true">std::vector&lt;Employees&gt; findEmployees(std::optional&lt;std::string&gt; const&amp; firstName, std::optional&lt;std::string&gt; const&amp; lastName);</pre>
<p><code>optional</code> is available in the standard library in C++17, and has been in Boost for a long time before that.</p>
<p>To retrieve all the employees that have the first name &#8220;John&#8221;, we can pass it as a first parameter and pass an empty optional as a second parameter:</p>
<pre class="lang:c++ decode:true">findEmployees("John", std::nullopt)</pre>
<p>And similarly, to get all the employees that belong to the Doe family:</p>
<pre class="lang:c++ decode:true">findEmployees(std::nullopt, "Doe")</pre>
<p>This interface gets the job done, but has at least two problems, which are related:</p>
<p><span style="text-decoration: underline;">Problem #1</span>: the parameter <code>std::nullopt</code> express that we pass &#8220;no&#8221; parameter. But at call site, it hides what role this parameter should have had in the function. It&#8217;s no parameter, but no what? No first name? No last name? No something else?</p>
<p><span style="text-decoration: underline;">Problem #2</span>: with the meaning of this parameter hidden, it becomes arguably even easier to mix up the order of parameters: <code>findEmployees(std::nullopt, "Doe")</code> looks very much like <code>findEmployees("Doe", std::nullopt)</code>, since both have only one &#8220;real&#8221; parameter.<br />
And it gets more confusing if there are more parameters: <code>findEmployees(std::nullopt, "Doe", std::nullopt)</code>, with the third parameter representing, say, the department of the employee. It then becomes harder to see if &#8220;Doe&#8221; really is at the correct position between the <code>std::nullopt</code>s.</p>
<h3><span style="color: #ff6600;">Strong optionals</span></h3>
<p>Clarifying the role of each parameter of an interface sounds like a job for <a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/">strong types</a>. Would it be possible to have a &#8220;strong optional&#8221;, that doesn&#8217;t use <code>std::nullopt</code> as a default parameter, but something more specific to its meaning instead?</p>
<p>Let&#8217;s design a class around that constraint.</p>
<p>This class would be essentially like an optional, but with an additional type <code>NoValue</code> that represents an empty value. It would have a <code>is-implemented-in-terms-of</code> relationship with optional, so we model this by containing an optional inside the class (see <a href="https://www.amazon.com/gp/product/0321334876/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321334876&amp;linkCode=as2&amp;tag=fluentcpp-20&amp;linkId=c827183fcb052e6a805d39ee7d66095">Effective C++</a> items 32 and 38 for more about how to express the various relationship between entities in C++):</p>
<pre class="lang:c++ decode:true">template&lt;typename T, typename NoValue&gt;
class NamedOptional
{
private:
    std::optional&lt;T&gt; o_;
};</pre>
<p>Its interface would resemble the one of <code>std::optional</code> except that it could be constructible from its <code>NoValue</code> type:</p>
<pre class="lang:c++ decode:true">    NamedOptional(NoValue) noexcept : o_(){}</pre>
<p>Now here is all the code put together. The interface of <code>std::optional</code> is richer than meets the eye so if you don&#8217;t like to look at tedious code, don&#8217;t look at this thorough forwarding to the interface of <code>std::optional</code>:</p>
<pre class="minimize:true lang:c++ decode:true ">template&lt;typename T, typename NoValue&gt;
class NamedOptional
{
public:
    NamedOptional() noexcept : o_() {}
    NamedOptional(NoValue) noexcept : o_(){}
    constexpr NamedOptional(const NamedOptional&amp; other) : o_(other.o_) {}
    constexpr NamedOptional( NamedOptional&amp;&amp; other ) noexcept : o_(std::move(other.o_)){}
    template &lt; class U &gt;
    NamedOptional( const NamedOptional&lt;U, NoValue&gt;&amp; other ) : o_(other.o_) {}
    template &lt; class U &gt;
    NamedOptional( NamedOptional&lt;U, NoValue&gt;&amp;&amp; other ) : o_(std::move(other.o_)){}
    template&lt; class... Args &gt; 
    constexpr explicit NamedOptional( std::in_place_t, Args&amp;&amp;... args ) : o_(std::in_place, std::forward&lt;Args...&gt;(args...)){}
    template&lt; class U, class... Args &gt;
    constexpr explicit NamedOptional( std::in_place_t,
                                 std::initializer_list&lt;U&gt; ilist, 
                                 Args&amp;&amp;... args ) : o_(std::in_place, ilist, std::forward&lt;Args...&gt;(args...)){}
    template&lt;typename U = T&gt;
    NamedOptional(U&amp;&amp; x) : o_(std::forward&lt;U&gt;(x)){}
    NamedOptional&amp; operator=( NoValue ) noexcept { o_ = std::nullopt; }
    NamedOptional&amp; operator=( const NamedOptional&amp; other ) { o_ = other.o_; }
    NamedOptional&amp; operator=( NamedOptional&amp;&amp; other ) noexcept(std::is_nothrow_move_assignable&lt;T&gt;::value &amp;&amp; std::is_nothrow_move_constructible&lt;T&gt;::value) { o_ = std::move(other.o_); }
    template&lt; class U = T &gt; 
    NamedOptional&amp; operator=( U&amp;&amp; value ) { o_ = std::forward&lt;U&gt;(value); }
    template&lt; class U &gt;
    NamedOptional&amp; operator=( const NamedOptional&lt;U, NoValue&gt;&amp; other ) { o_ = other.o_; }
    template&lt; class U &gt;
    NamedOptional&amp; operator=( NamedOptional&lt;U, NoValue&gt;&amp;&amp; other ) { o_ = std::forward&lt;U&gt;(value); }
    constexpr std::optional&lt;T&gt; const&amp; operator-&gt;() const { return o_; }
    constexpr std::optional&lt;T&gt;&amp; operator-&gt;() { return o_; }
    constexpr const T&amp; operator*() const&amp; { return *o_; }
    constexpr T&amp; operator*() &amp; { return *o_; }
    constexpr const T&amp;&amp; operator*() const&amp;&amp; { return *std::move(o_); }
    constexpr T&amp;&amp; operator*() &amp;&amp; { return *std::move(o_); }
    explicit operator bool () const { return static_cast&lt;bool&gt;(o_); }
    constexpr bool has_value() const noexcept { return o_.has_value(); }
    constexpr T&amp; value() &amp; { return o_.value(); }
    constexpr const T &amp; value() const &amp;  { return o_.value(); }
    constexpr T&amp;&amp; value() &amp;&amp;  { return std::move(o_).value(); }
    constexpr const T&amp;&amp; value() const &amp;&amp; { return std::move(o_).value(); }
    template&lt; class U &gt; 
    constexpr T value_or( U&amp;&amp; default_value ) const&amp; { return o_.value_or(std::forward&lt;U&gt;(default_value)); }
    template&lt; class U &gt; 
    constexpr T value_or( U&amp;&amp; default_value ) &amp;&amp; { return std::move(o_).value_or(std::forward&lt;U&gt;(default_value)); }
    void swap( NamedOptional&amp; other ) noexcept { return o_.swap(other.o_); }
    void reset() noexcept { o_.reset(); }
    template&lt; class... Args &gt; 
    T&amp; emplace( Args&amp;&amp;... args ) { return o_.emplace(std::forward&lt;Args...&gt;(args...)); }
    template&lt; class U, class... Args &gt; 
    T&amp; emplace( std::initializer_list&lt;U&gt; ilist, Args&amp;&amp;... args ) { return o_.emplace(ilist, std::forward&lt;Args...&gt;(args...)); }

    template&lt; class U &gt; friend constexpr bool operator==( const NamedOptional&amp; lhs, const NamedOptional&lt;U, NoValue&gt;&amp; rhs ) { return lhs.o_ == rhs.o_; }
    template&lt; class U &gt; friend constexpr bool operator!=( const NamedOptional&amp; lhs, const NamedOptional&lt;U, NoValue&gt;&amp; rhs ) { return lhs.o_ != rhs.o_; }
    template&lt; class U &gt; friend constexpr bool operator&lt;( const NamedOptional&amp; lhs, const NamedOptional&lt;U, NoValue&gt;&amp; rhs ) { return lhs.o_ &lt; rhs.o_; }
    template&lt; class U &gt; friend constexpr bool operator&lt;=( const NamedOptional&amp; lhs, const NamedOptional&lt;U, NoValue&gt;&amp; rhs ) { return lhs.o_ &lt;= rhs.o_; }
    template&lt; class U &gt; friend constexpr bool operator&gt;( const NamedOptional&amp; lhs, const NamedOptional&lt;U, NoValue&gt;&amp; rhs ) { return lhs.o_ &gt; rhs.o_; }
    template&lt; class U &gt; friend constexpr bool operator&gt;=( const NamedOptional&amp; lhs, const NamedOptional&lt;U, NoValue&gt;&amp; rhs ) { return lhs.o_ &gt;= rhs.o_; }

    friend constexpr bool operator==( const NamedOptional&amp; lhs, NoValue) { return lhs.o_ == std::nullopt; }
    friend constexpr bool operator!=( const NamedOptional&amp; lhs, NoValue) { return lhs.o_ != std::nullopt; }
    friend constexpr bool operator&lt; ( const NamedOptional&amp; lhs, NoValue) { return lhs.o_ &lt;  std::nullopt; }
    friend constexpr bool operator&lt;=( const NamedOptional&amp; lhs, NoValue) { return lhs.o_ &lt;= std::nullopt; }
    friend constexpr bool operator&gt; ( const NamedOptional&amp; lhs, NoValue) { return lhs.o_ &gt;  std::nullopt; }
    friend constexpr bool operator&gt;=( const NamedOptional&amp; lhs, NoValue) { return lhs.o_ &gt;= std::nullopt; }
    friend constexpr bool operator==( NoValue, const NamedOptional&amp; rhs) { return std::nullopt == rhs.o_; }
    friend constexpr bool operator!=( NoValue, const NamedOptional&amp; rhs) { return std::nullopt != rhs.o_; }
    friend constexpr bool operator&lt; ( NoValue, const NamedOptional&amp; rhs) { return std::nullopt &lt;  rhs.o_; }
    friend constexpr bool operator&lt;=( NoValue, const NamedOptional&amp; rhs) { return std::nullopt &lt;= rhs.o_; }
    friend constexpr bool operator&gt; ( NoValue, const NamedOptional&amp; rhs) { return std::nullopt &gt;  rhs.o_; }
    friend constexpr bool operator&gt;=( NoValue, const NamedOptional&amp; rhs) { return std::nullopt &gt;= rhs.o_; }

    template&lt; class U &gt; friend constexpr bool operator==( const NamedOptional&amp; lhs, const U&amp; value) { return lhs.o_ == value; }
    template&lt; class U &gt; friend constexpr bool operator!=( const NamedOptional&amp; lhs, const U&amp; value) { return lhs.o_ != value; }
    template&lt; class U &gt; friend constexpr bool operator&lt; ( const NamedOptional&amp; lhs, const U&amp; value) { return lhs.o_ &lt;  value; }
    template&lt; class U &gt; friend constexpr bool operator&lt;=( const NamedOptional&amp; lhs, const U&amp; value) { return lhs.o_ &lt;= value; }
    template&lt; class U &gt; friend constexpr bool operator&gt; ( const NamedOptional&amp; lhs, const U&amp; value) { return lhs.o_ &gt;  value; }
    template&lt; class U &gt; friend constexpr bool operator&gt;=( const NamedOptional&amp; lhs, const U&amp; value) { return lhs.o_ &gt;= value; }
    template&lt; class U &gt; friend constexpr bool operator==( const U&amp; value, const NamedOptional&amp; rhs) { return value == rhs.o_; }
    template&lt; class U &gt; friend constexpr bool operator!=( const U&amp; value, const NamedOptional&amp; rhs) { return value != rhs.o_; }
    template&lt; class U &gt; friend constexpr bool operator&lt; ( const U&amp; value, const NamedOptional&amp; rhs) { return value &lt;  rhs.o_; }
    template&lt; class U &gt; friend constexpr bool operator&lt;=( const U&amp; value, const NamedOptional&amp; rhs) { return value &lt;= rhs.o_; }
    template&lt; class U &gt; friend constexpr bool operator&gt; ( const U&amp; value, const NamedOptional&amp; rhs) { return value &gt;  rhs.o_; }
    template&lt; class U &gt; friend constexpr bool operator&gt;=( const U&amp; value, const NamedOptional&amp; rhs) { return value &gt;= rhs.o_; }

    friend size_t std::hash&lt;NamedOptional&lt;T, NoValue&gt;&gt;::operator()(NamedOptional&lt;T, NoValue&gt; const&amp; x) const;
private:
    std::optional&lt;T&gt; o_;
};

namespace std
{
template&lt; typename T, typename NoValue &gt;
void swap( NamedOptional&lt;T, NoValue&gt;&amp; lhs, NamedOptional&lt;T, NoValue&gt;&amp; rhs ) noexcept(noexcept(lhs.swap(rhs))) { return lhs.swap(rhs); }

template&lt;typename T, typename NoValue&gt;
struct hash&lt;NamedOptional&lt;T, NoValue&gt;&gt;
{
    size_t operator()(NamedOptional&lt;T, NoValue&gt; const&amp; x) const
    {
        return std::hash&lt;T&gt;()(x.o_);
    }
};
}</pre>
<h4><span style="color: #ff6600;">Isn&#8217;t it like Boost Outcome / <code>std::expected</code>?</span></h4>
<p>This <code>NamedOptional</code> component represents a value that could be there or not, and has an additional template parameter. From afar, this can look a bit like <a href="https://ned14.github.io/outcome/" target="_blank" rel="noopener">Outcome</a> that is in Boost, or to its yet-to-be standard counterpart <code>std::expected</code>.</p>
<p>But when we get closer, we can see <code>NamedOptional</code> doesn&#8217;t represent the same thing as those two. Indeed, Outcome and <code>expected</code> represent a piece of data that could be empty, but accompanied with a piece of information that gives details about <strong>why</strong> it is empty. This is more powerful that <code>optional</code> or <code>NamedOptional</code> in this regard, as they only contain the binary information that the value is empty or not.</p>
<p>In our case we don&#8217;t need to know why it isn&#8217;t there. It is a partial query, so it is expected that some parameters are not specified. So <code>optional</code> and <code>expected</code> can serve different purposes, and <code>NamedOptional</code> is closer to optional and adds a more explicit names to the empty values.</p>
<h3><span style="color: #ff6600;">Strong types + strong optionals</span></h3>
<p>Let&#8217;s now use this strong optional to express that an empty parameter can mean &#8220;no first name&#8221; or &#8220;no last name&#8221;, and that those two mean a different thing:</p>
<pre class="lang:c++ decode:true">struct NoFirstName{};
using OptionalFirstName = NamedOptional&lt;std::string, NoFirstName&gt;;

struct NoLastName{};
using OptionalLastName = NamedOptional&lt;std::string, NoLastName&gt;;</pre>
<p>EDIT: after discussing this with Ivan Čukić, we realized that &#8220;AnyFirstName&#8221; was better expressing the intention of &#8220;we don&#8217;t specify a first name because it could be any first name&#8221; than &#8220;NoFirstName&#8221;:</p>
<pre class="lang:c++ decode:true ">struct AnyFirstName{};
using OptionalFirstName = NamedOptional&lt;std::string, AnyFirstName&gt;;

struct AnyLastName{};
using OptionalLastName = NamedOptional&lt;std::string, AnyLastName&gt;;</pre>
<p>Note that, contrary to the usual definitions of <a href="https://github.com/joboccara/NamedType" target="_blank" rel="noopener"><code>NamedType</code></a>s, we can&#8217;t declare <code>AnyFirstName</code> inside the using declaration, because since we are going to instantiate it, we need a definition and not just a declaration.</p>
<p>To get all the employees of the Doe family we now have to write:</p>
<pre class="lang:c++ decode:true">findEmployees(AnyFirstName(), "Doe");</pre>
<p>which provides a solution to problems #1 and #2 above: we know what the empty argument stand for, and mixing up the arguments would not compile:</p>
<pre class="lang:c++ decode:true">findEmployees("Doe", AnyFirstName()); // compilation error</pre>
<p>because the second parameter, an <code>Optional<strong>Last</strong>Name</code>, cannot be constructed from a <code>Any<strong>First</strong>Name</code>.</p>
<p>To go further in clarifying the meaning of those function parameters, we can combine strong optionals with strong types:</p>
<pre class="lang:c++ decode:true">using FirstName = NamedType&lt;std::string, struct FirstNameTag&gt;;
struct AnyFirstName{};
using OptionalFirstName = NamedOptional&lt;FirstName, AnyFirstName&gt;;

using LastName = NamedType&lt;std::string, struct LastNameTag&gt;;
struct AnyLastName{};
using OptionalLastName = NamedOptional&lt;LastName, AnyLastName&gt;;</pre>
<p>which leads to this type of call site:</p>
<pre class="lang:c++ decode:true">findEmployees(AnyFirstName(), LastName("Doe"));</pre>
<p>The purpose of this development was to clarify the role of each of the (possibly empty) parameters of the function.</p>
<p>Now that you&#8217;ve seen the problem and a possible solution, it&#8217;s your turn to express your opinion on this!</p>
<p>Do you think there is a need for strong optionals? Do you see another way to go about this issue?</p>
<p><strong>You may also like:</strong></p>
<ul>
<li><a href="https://www.fluentcpp.com/2016/12/01/partial-queries-with-optionalt/">Partial queries with optional&lt;T&gt;</a></li>
<li><a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/">Strong types for strong interfaces</a></li>
<li><a href="https://www.fluentcpp.com/2016/11/24/clearer-interfaces-with-optionalt/">Clearer interfaces with optional&lt;T&gt;</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F16%2Fstrong-optionals%2F&#038;t=Strong%20Optionals&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F16%2Fstrong-optionals%2F&#038;p&#091;images&#093;&#091;0&#093;=https%3A%2F%2Fi0.wp.com%2Fwww.fluentcpp.com%2Fwp-content%2Fuploads%2F2018%2F01%2Fstrong_optionals2.png%3Ffit%3D1280%252C720%26ssl%3D1&#038;p&#091;title&#093;=Strong%20Optionals" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F16%2Fstrong-optionals%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F16%2Fstrong-optionals%2F&#038;title=Strong%20Optionals" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2018/01/16/strong-optionals/">Strong Optionals</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.fluentcpp.com/2018/01/16/strong-optionals/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2583</post-id>	</item>
		<item>
		<title>Strong Templates</title>
		<link>https://www.fluentcpp.com/2018/01/09/strong-templates/</link>
					<comments>https://www.fluentcpp.com/2018/01/09/strong-templates/#comments</comments>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Tue, 09 Jan 2018 01:00:49 +0000</pubDate>
				<category><![CDATA[Strong types]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[expressive]]></category>
		<category><![CDATA[interface]]></category>
		<category><![CDATA[strong template]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=2575</guid>

					<description><![CDATA[<p>Strong typing consists in creating a new type that stands for another type and adds meaning through its name. What would it look like to apply this idea to template interfaces? Disclaimer: What you&#8217;ll see in this post is experimental, and it&#8217;d be great to have your feedback on it at the end. Strong types for [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2018/01/09/strong-templates/">Strong Templates</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Strong typing consists in creating a new type that stands for another type and adds <strong>meaning</strong> through its <strong>name</strong>. What would it look like to apply this idea to <strong>template interfaces</strong>?</p>
<p>Disclaimer: What you&#8217;ll see in this post is experimental, and it&#8217;d be great to have your feedback on it at the end.</p>
<h3><span style="color: #ff6600;">Strong types for strong interfaces</span></h3>
<p>We&#8217;ve talked a lot about how strong types can help <a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/">clarify interfaces</a>. Here is a quick example, that you can safely skip if you&#8217;re already familiar with strong types.</p>
<p>Consider a case where we want to represent in code the concept of rows and columns.</p>
<p>We could use <code>int</code>s to represent both, but doing this doesn&#8217;t carry any information about what those <code>int</code> represents, and that can even get confusing in an interface:</p>
<pre class="lang:c++ decode:true">void setPosition(int row, int column);</pre>
<p>Indeed, this interface expects a row first and then a column, but you can&#8217;t see that at call site:</p>
<pre class="lang:c++ decode:true">setPosition(12, 14);</pre>
<p>When writing that code, there is a risk of mixing up the row and the column. And when someone reads it, they can&#8217;t know whether 12 represents the row, the column, or even something completely unrelated.</p>
<p>Well, in theory, they can. They can go look up the definition of <code>setPosition</code> and check which parameters means what. But we don&#8217;t want the people that read our code to go look up the definition of every function we use, do we?</p>
<p>So we can define two dedicated types: <code>Row</code> and <code>Column</code>. Let&#8217;s do this by using the <a href="https://github.com/joboccara/NamedType" target="_blank" rel="noopener">NamedType</a> library:</p>
<pre class="lang:c++ decode:true">using Row = NamedType&lt;int, struct RowTag&gt;;
using Column = NamedType&lt;int, struct ColumnTag&gt;;</pre>
<p>This reads: &#8220;<code>Row</code> is like an <code>int</code>, but it&#8217;s a different type with a name stuck on it that says it&#8217;s a row, and not just any <code>int</code>&#8220;. And same for <code>Column.</code></p>
<p>Using them clarifies the intent of the interface:</p>
<pre class="lang:c++ decode:true ">void setPosition(Row row, Column column);</pre>
<p>which leads to both a more expressive code at call site:</p>
<pre class="lang:c++ decode:true">setPosition(Row(12), Column(14));</pre>
<p>and more safety against the risk of mixing up the parameters. Indeed, the following would not compile since <code>Row</code> and <code>Column</code> are two different types:</p>
<pre class="lang:c++ decode:true">setPosition(Column(14), Row(12)); // compilation error!</pre>
<p>This example was a function interface, but this idea can be also applied to <strong>template interfaces</strong>.</p>
<h3><span style="color: #ff6600;">Template interface</span></h3>
<p>By template interface, I mean a template instantiation out of which we can get a result.</p>
<p>Here is a simple one in the standard library since C++11 (but that could be replicated even in C++98):</p>
<pre class="lang:c++ decode:true">template&lt; typename Base, typename Derived &gt;
struct is_base_of;</pre>
<p><code>is_base_of</code> &#8220;returns&#8221; a boolean that indicates whether or not the first template parameter is a base class of the second template parameter.</p>
<p>Such a template interface has several ways of &#8220;returning&#8221; something that depends on its template parameters. In this particular case it returns a value, and the convention for it is that this value is stored in a static public constant member of the class, called <code>value</code>.</p>
<p>So, if <code>Derived</code> derives from <code>Base</code> then <code>is_base_of&lt;Base, Derived&gt;::value</code> is <code>true</code>. Otherwise, it is <code>false</code>.</p>
<p>And in C++14 appear template variables, which let us store the result into a variable, encapsulating the <code>::value</code>:</p>
<pre class="lang:c++ decode:true ">template&lt;typename Base, typename Derived&gt;
constexpr bool is_base_of_v = std::is_base_of&lt;Base, Derived&gt;::value;
</pre>
<p>(despite being technically doable in C++14, <code>is_base_of_v</code> becomes standard in C++17).</p>
<p>This looks OK. But what if, like it is in reality, our types are not called <code>Base</code> and <code>Derived</code>? What if they&#8217;re called <code>A</code> and <code>B</code> (which are not realistic names either, hopefully, but this is to illustrate the case where the name don&#8217;t show which is the base and which is the derived)?</p>
<pre class="lang:c++ decode:true">is_base_of_v&lt;A, B&gt;</pre>
<p>What does the above mean? Should this read &#8220;<code>A</code> is the base of <code>B</code>&#8220;, or rather &#8220;<code>B</code> is the base of <code>A</code>&#8220;? I suppose the first one is more likely, but the interface doesn&#8217;t express it explicitly.</p>
<p>To quote Andrei Alexandrescu in <a href="https://www.amazon.com/gp/product/0201704315/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0201704315&amp;linkCode=as2&amp;tag=fluentcpp-20&amp;linkId=5aeb3f292048e43723ef58985015c6e6">Modern C++ Design</a>:</p>
<div class="page" title="Page 46">
<div class="layoutArea">
<div class="column">
<blockquote><p>Why use SUPERSUBCLASS and not the cuter <strong>BASE_OF</strong> or INHERITS? For a very practical reason. Initially Loki used INHERITS. But with INHERITS(T, U) it was a constant struggle to say which way the test worked—did it tell whether T inherited U or vice versa?</p></blockquote>
</div>
</div>
</div>
<p>Let&#8217;s try to apply the ideas of strong typing that we saw above to this template interface.</p>
<h3><span style="color: #ff6600;">Strong templates</span></h3>
<p>So, just like we had <code>Row(12)</code> and <code>Column(14)</code>, the purpose is to have something resembling <code>Base(A)</code> and <code>Derived(B)</code>.</p>
<p>Since these are template types, let&#8217;s create a template <code>Base</code> and a template <code>Derived</code>, which exist just for the sake of being there and don&#8217;t contain anything:</p>
<pre class="lang:c++ decode:true">template&lt;typename T&gt;
struct Base{};

template&lt;typename T&gt;
struct Derived{};</pre>
<p>We can then use those two templates to wrap the parameters of the <code>is_base_of</code> interface. Just for fun, let&#8217;s call that <code>strong_is_base_of</code>:</p>
<pre class="lang:c++ decode:true ">template&lt;typename, typename&gt;
constexpr bool strong_is_base_of_v;

template&lt;typename base, typename derived&gt;
constexpr bool strong_is_base_of_v&lt;Base&lt;base&gt;, Derived&lt;derived&gt;&gt; = is_base_of_v&lt;base, derived&gt;;
</pre>
<p>Note that, contrary to the usual strong typing we do on types, we don&#8217;t need an equivalent of the <code>.get()</code> method here. This is because templates use pattern matching of types (this is why there is a primary template that is declared but not defined, and a secondary template with a specific pattern containing <code>Base</code> and <code>Derived</code> that is fully defined).</p>
<p>The above uses C++14 template variables (that can be <a href="https://www.fluentcpp.com/2017/08/11/how-to-do-partial-template-specialization-in-c/">partially specialized</a>).</p>
<p>Here is what it looks like <strong>before C++14</strong> without variable templates:</p>
<pre class="lang:c++ decode:true ">template&lt;typename, typename&gt;
struct strong_is_base_of{};

template&lt;typename base, typename derived&gt;
struct strong_is_base_of&lt;Base&lt;base&gt;, Derived&lt;derived&gt;&gt; : std::is_base_of&lt;base, derived&gt; {};</pre>
<p>It is designed along the same lines of the C++14 solution, but uses inheritance of <code>is_base_of</code> to bring in the <code>value</code> member instead of a variable template.</p>
<h4><span style="color: #ff6600;">Usage</span></h4>
<p>Let&#8217;s now see what this looks like at call site, which was the point of all this implementation!</p>
<p>Let&#8217;s use a type <code>A</code> that is the base class of a type <code>B</code>:</p>
<pre class="lang:c++ decode:true">class A
{
    // ...
};

class B : public A
{
    // ...
};</pre>
<p>Here is how to check that <code>A</code> is indeed a base class of <code>B</code>, as the following compiles:</p>
<pre class="lang:c++ decode:true">static_assert( strong_is_base_of_v&lt;Base&lt;A&gt;, Derived&lt;B&gt;&gt;, "A is a base of B");
</pre>
<p>The point of this is to make it explicit in code that we&#8217;re determining whether <code>A</code> is the <code>Base</code> and <code>B</code> is the <code>Derived</code>, and not the opposite.</p>
<p>We now check that <code>B</code> is not a base class of <code>A</code>:</p>
<pre class="lang:c++ decode:true">static_assert( !strong_is_base_of_v&lt;Base&lt;B&gt;, Derived&lt;A&gt;&gt;, "B is not the base of A");</pre>
<p>And if we accidentally mix up the arguments, by passing in the derived class first:</p>
<pre class="lang:c++ decode:true ">strong_is_base_of_v&lt;Derived&lt;A&gt;, Base&lt;B&gt;&gt;</pre>
<p>It does not compile. What is happening is that this expression calls the primary template of <code>strong_is_base_of_v</code>, that has no definition.</p>
<h3><span style="color: #ff6600;"><code>NamedTemplate</code></span></h3>
<p>In the above code, the two definitions of the <code>Base</code> and <code>Derived</code> templates don&#8217;t mention that they exist for the purpose of strong typing:</p>
<pre class="lang:c++ decode:true ">template&lt;typename T&gt;
struct Base{};

template&lt;typename T&gt;
struct Derived{};</pre>
<p>Maybe it&#8217;s ok. But if we compare that to the usual definition of a strong type:</p>
<pre class="lang:c++ decode:true ">using Row = NamedType&lt;int, struct RowTag&gt;;</pre>
<p>We see that the latter definition shows that it is a strong type. Can we have a similar definition for a strong template?</p>
<p>To achieve that, we can define a <code>NamedTemplate</code> template;</p>
<pre class="lang:c++ decode:true ">template&lt;typename T, typename Tag&gt;
class NamedTemplate {};
</pre>
<p>Which we can use to define our strong templates <code>Base</code> and <code>Derived</code>:</p>
<pre class="lang:c++ decode:true ">template&lt;typename T&gt;
using Base = NamedTemplate&lt;T, struct BaseTag&gt;;

template&lt;typename T&gt;
using Derived = NamedTemplate&lt;T, struct DerivedTag&gt;;
</pre>
<p>Which has the advantage of expressing that <code>Base</code> and <code>Derived</code> are &#8220;strong templates&#8221;, but also has the drawback of adding more code to figure out.</p>
<p>As this technique is experimental, I&#8217;m writing it as a basis for discussion rather than a finished product. So if you have an opinion on this, it&#8217;s the moment to chip in!</p>
<p>More specifically:</p>
<p><span style="color: #ff6600;">1) Do you think that the concept of strong typing makes sense in a template interface, like it does in a normal interface?</span></p>
<p><span style="color: #ff6600;">2) What do you think of the resulting code calling the strong <code>is_base_of</code>?</span></p>
<p><span style="color: #ff6600;">3) Do you think there is a need to express that <code>Base</code> and <code>Derived</code> are strong templates in their definition?</span></p>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F09%2Fstrong-templates%2F&#038;t=Strong%20Templates&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F09%2Fstrong-templates%2F&#038;p&#091;images&#093;&#091;0&#093;=https%3A%2F%2Fi0.wp.com%2Fwww.fluentcpp.com%2Fwp-content%2Fuploads%2F2017%2F11%2Fstrong_templates2.png%3Ffit%3D1280%252C720%26ssl%3D1&#038;p&#091;title&#093;=Strong%20Templates" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F09%2Fstrong-templates%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F09%2Fstrong-templates%2F&#038;title=Strong%20Templates" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2018/01/09/strong-templates/">Strong Templates</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.fluentcpp.com/2018/01/09/strong-templates/feed/</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2575</post-id>	</item>
		<item>
		<title>Making Strong Types Implicitly Convertible</title>
		<link>https://www.fluentcpp.com/2018/01/05/making-strong-types-implicitly-convertible/</link>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Fri, 05 Jan 2018 01:00:12 +0000</pubDate>
				<category><![CDATA[Strong types]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[expressive]]></category>
		<category><![CDATA[fluent]]></category>
		<category><![CDATA[implicit conversion]]></category>
		<category><![CDATA[strong types]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=1806</guid>

					<description><![CDATA[<p>Strong types and implicit conversions, doesn&#8217;t this sound like incompatible features ? It can be argued that they are compatible, in fact. We saw why it could be useful to inherit from the underlying type&#8217;s features, and if the underlying type is implicitly convertible to something then you might want to inherit that feature too [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2018/01/05/making-strong-types-implicitly-convertible/">Making Strong Types Implicitly Convertible</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Strong types and implicit conversions, doesn&#8217;t this sound like incompatible features ?</p>
<p>It can be argued that they are compatible, in fact. We saw why it could be useful to <a href="https://www.fluentcpp.com/2017/05/23/strong-types-inheriting-functionalities-from-underlying/">inherit from the underlying type&#8217;s features</a>, and if the underlying type is implicitly convertible to something then you might want to inherit that feature too for your strong type.</p>
<p>In fact, <code>NamedType</code> user Jan Koniarik expressed on <a href="https://twitter.com/SquirrelCZE/status/889451177758400515" target="_blank" rel="noopener">Twitter</a> a need for exactly this feature for the <a href="https://github.com/joboccara/namedtype">NamedType </a>library. I think the need is interesting, and some aspects of the implementation are worth considering too; which is why I&#8217;m sharing this with you today.</p>
<p>This article is part of the series on strong types:</p>
<ul>
<li><a href="https://www.fluentcpp.com/2016/12/05/named-constructors/" target="_blank" rel="noopener noreferrer">Strongly typed constructors</a></li>
<li><a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/" target="_blank" rel="noopener noreferrer">Strong types for strong interfaces</a></li>
<li><a href="https://www.fluentcpp.com/2017/03/06/passing-strong-types-reference-revisited/" target="_blank" rel="noopener noreferrer">Passing strong types by reference</a></li>
<li><a href="https://www.fluentcpp.com/2017/02/20/strong-lambdas-strong-generic-types/" target="_blank" rel="noopener noreferrer">Strong lambdas: strong typing over generic types</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/05/news-strong-types-are-free/">Good news: strong types are (mostly) free in C++</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/23/strong-types-inheriting-functionalities-from-underlying/" target="_blank" rel="noopener noreferrer">Inheriting functionalities from the underlying type</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/30/implementing-a-hash-function-for-strong-types/" target="_blank" rel="noopener noreferrer">Making strong types hashable</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/26/strong-types-conversions/" target="_blank" rel="noopener noreferrer">Converting strong units to one another</a></li>
<li><a href="https://www.fluentcpp.com/2017/08/08/metaclasses-ultimate-answer-strong-typing-c/">Metaclasses, the Ultimate Answer to Strong Typing in C++?</a></li>
<li>Making strong types implicitly convertible</li>
</ul>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-2835" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/srtong-types-implicit-conversions.png?resize=1280%2C720&#038;ssl=1" alt="Strong types implicit conversions" width="1280" height="720" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/srtong-types-implicit-conversions.png?w=1280&amp;ssl=1 1280w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/srtong-types-implicit-conversions.png?resize=150%2C84&amp;ssl=1 150w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/srtong-types-implicit-conversions.png?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/srtong-types-implicit-conversions.png?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/srtong-types-implicit-conversions.png?resize=1024%2C576&amp;ssl=1 1024w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/srtong-types-implicit-conversions.png?resize=32%2C18&amp;ssl=1 32w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/srtong-types-implicit-conversions.png?resize=178%2C100&amp;ssl=1 178w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/srtong-types-implicit-conversions.png?resize=201%2C113&amp;ssl=1 201w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/srtong-types-implicit-conversions.png?resize=350%2C197&amp;ssl=1 350w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/srtong-types-implicit-conversions.png?resize=711%2C400&amp;ssl=1 711w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/srtong-types-implicit-conversions.png?resize=782%2C440&amp;ssl=1 782w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/srtong-types-implicit-conversions.png?resize=960%2C540&amp;ssl=1 960w" sizes="(max-width: 1000px) 100vw, 1000px" data-recalc-dims="1" /></p>
<h3><span style="color: #ff6600;">Adding an <code>ImplicitlyConvertibleTo</code> skill</span></h3>
<p>The functionalities inherited from the underlying type, also named &#8220;Skills&#8221; in the NamedType library, are grouped into separate classes using the <a href="https://www.fluentcpp.com/2017/05/12/curiously-recurring-template-pattern/">CRTP pattern</a>. For example, to reuse the <code>operator+</code> of the underlying type the <code>Addable</code> skill looks like this:</p>
<pre class="lang:c++ decode:true">template &lt;typename T&gt;
struct Addable : crtp&lt;T, Addable&gt;
{
    T operator+(T const&amp; other) const { return T(this-&gt;underlying().get() + other.get()); }
};</pre>
<p>The <code>crtp</code> class that this skill inherits from is a helper that gives easy access the underlying of the CRTP, that is the class that inherits from it. If you&#8217;re curious about this you can check it all out in the post on <a href="https://www.fluentcpp.com/2017/05/19/crtp-helper/">the CRTP helper</a>.</p>
<p>If the type <code>T</code> that NamedType is strengthening is convertible, say to <code>int</code>, then we can implement a skills that performs an implicit conversion of the strong type to an <code>int</code>:</p>
<pre class="lang:c++ decode:true">template &lt;typename T&gt;
struct ImplicitlyConvertibleToInt : crtp&lt;T, ImplicitlyConvertibleToInt&gt;
{
    operator int() const
    {
        return this-&gt;underlying().get();
    }
};
</pre>
<p>Fine. But <code>int</code> is a very specific case, our type <code>T</code> could be implicitly convertible to anything. It seems natural to template this class on the destination type of the conversion.</p>
<p>But there is a problem, this class is already a template! How can we template a class that&#8217;s already a template?</p>
<p>I suggest you pause for just a moment and try to think about how you would do it.</p>
<p>(<img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f3b6.png" alt="🎶" class="wp-smiley" style="height: 1em; max-height: 1em;" /> musical interlude <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f3b6.png" alt="🎶" class="wp-smiley" style="height: 1em; max-height: 1em;" />)</p>
<p>Done?</p>
<p>One way to go about this is to wrap this template class into another template class. This comes from a fairly common metaprogramming technique, whose naming convention is to call the inner template class &#8220;templ&#8221;. Let&#8217;s do this:</p>
<pre class="lang:c++ decode:true">template &lt;typename Destination&gt;
struct ImplicitlyConvertibleTo
{
    template &lt;typename T&gt;
    struct templ : crtp&lt;T, templ&gt;
    {
        operator Destination() const
        {
            return this-&gt;underlying().get();
        }
    };
    
};</pre>
<p>Since the underlying type can have implicit conversions, I think it&#8217;s right to offer the possibility to the strong type to inherit that feature. It&#8217;s just a possibility, your strong type doesn&#8217;t have to have an <code>ImplicitlyConvertibleTo</code> skill even if its underlying type supports implicit conversions.</p>
<h3><span style="color: #ff6600;">The two directions of implicit conversions</span></h3>
<p><span style="font-size: 16px;">We can now use this skill in our instantiation of NamedType. Let&#8217;s test it with a type A that is convertible to B because it implements an implicit conversion operator:</span></p>
<pre class="lang:c++ decode:true ">struct B
{

};

struct A
{
    operator B () const { return B(); }
};</pre>
<p>Then a strong type over <code>A</code> could keep this propriety of being convertible to <code>B</code>:</p>
<pre class="lang:c++ decode:true">using StrongA = NamedType&lt;A, struct StrongATag, ImplicitlyConvertibleTo&lt;B&gt;::templ&gt;;

B b = strongA; // implicit conversion here
</pre>
<p>There is another way for <code>A</code> to be convertible to <code>B</code>: if B has a constructor taking an <code>A</code> and that is not <code>explicit</code>:</p>
<pre class="lang:c++ decode:true ">struct A
{

};

struct B
{
    B(A const&amp; a){}
};</pre>
<p>The same usage of our <code>ImplicitlyConvertibleTo</code> skill works:</p>
<pre class="lang:c++ decode:true">using StrongA = NamedType&lt;A, struct StrongATag, ImplicitlyConvertibleTo&lt;B&gt;::templ&gt;;

B b = strongA; // another implicit conversion here</pre>
<p>You may have noticed the <code>::templ</code> in the client code. This is really annoying, and I must admit I didn&#8217;t find a way to make it disappear. I would have loved to rename the real skill something like <code>ImplicitlyConvertibleTo_impl</code> and declare an alias for the simpler name:</p>
<pre class="lang:c++ decode:true ">// Imaginary C++
template &lt;typename Destination&gt;
using ImplicitlyConvertibleTo = ImplicitlyConvertibleTo_Impl&lt;Destination&gt;::template templ;
</pre>
<p>But there is no such thing as an alias for template templates in C++. I&#8217;m not entirely sure why, but I understand that this feature was considered by the C++ committee, but didn&#8217;t make it into the standard (yet?).</p>
<p>So for the moment let&#8217;s stick with the trailing <code>::templ</code> in client code. If you see how to hide this, please, shout!</p>
<h3><span style="color: #ff6600;">Not made for calling functions</span></h3>
<p>At first sight, it seems that this sort of implicit conversion could be used to invoke a function that expects an underlying type by passing it a <code>NamedType</code> instead. Indeed, we could declare the <code>NamedType</code> to be implicitly convertible to its underlying type. This way we wouldn&#8217;t have to write a call to <code>.get()</code> every time we pass a <code>NamedType</code> to a function that existed before it:</p>
<pre class="lang:c++ decode:true">using Label = NamedType&lt;std::string, struct LabelTag, ImplicitlyConvertibleTo&lt;std::string&gt;::templ&gt;;

std::string toUpperCase(std::string const&amp; s);

void display(Label const&amp; label)
{
    std::cout &lt;&lt; toUpperCase(label) &lt;&lt; '\n';
}</pre>
<p>Indeed, without this skill we need to pass the underlying type taken from the <code>NamedType</code> explicitly:</p>
<pre class="lang:c++ mark:7 decode:true ">using Label = NamedType&lt;std::string, struct LabelTag&gt;;

std::string toUpperCase(std::string const&amp; s);

void display(Label const&amp; label)
{
    std::cout &lt;&lt; toUpperCase(label.get()) &lt;&lt; '\n';
}</pre>
<p>Of course, this stays an opt-in, that is to say you can choose whether or not not activate this conversion feature.</p>
<p>However, while I this implementation can be appropriate for implicit conversions in general, it isn&#8217;t the best solution for the case of calling functions on strong types. Indeed, looking back at our implicit conversion skill, its operator was defined like this:</p>
<pre class="lang:c++ decode:true ">operator Destination() const
{
    return this-&gt;underlying().get();
}</pre>
<p>In the above example, <code>Destination</code> is <code>std::string</code>.</p>
<p>Given that this method returns an object inside the class by value, it creates a <strong>copy</strong> of it. So if we use this to call function, it means that we&#8217;ll pass copies of the underlying value as arguments to the function. This has the drawbacks of potentially making a useless copy, and to prevent the function to bind to an argument (which can be useful &#8211; <code>std::back_inserter</code> does it for instance).</p>
<p>No, <code>ImplicitlyConvertible</code> works for implicit conversions, but for allowing to call functions we need something different. Something which is detailed in <a href="https://www.fluentcpp.com/2017/11/07/calling-functions-methods-strong-types/">Calling Functions and Methods on Strong Types</a>.</p>
<p>Related articles:</p>
<ul>
<li><a href="https://www.fluentcpp.com/2016/12/05/named-constructors/" target="_blank" rel="noopener noreferrer">Strongly typed constructors</a></li>
<li>What the Curiously Recurring Template Pattern can bring to your code</li>
<li><a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/" target="_blank" rel="noopener noreferrer">Strong types for strong interfaces</a></li>
<li><a href="https://www.fluentcpp.com/2017/03/06/passing-strong-types-reference-revisited/" target="_blank" rel="noopener noreferrer">Passing strong types by reference</a></li>
<li><a href="https://www.fluentcpp.com/2017/02/20/strong-lambdas-strong-generic-types/" target="_blank" rel="noopener noreferrer">Strong lambdas: strong typing over generic types</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/05/news-strong-types-are-free/">Good news: strong types are (mostly) free in C++</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/23/strong-types-inheriting-functionalities-from-underlying/" target="_blank" rel="noopener noreferrer">Inheriting functionalities from the underlying type</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/30/implementing-a-hash-function-for-strong-types/" target="_blank" rel="noopener noreferrer">Making strong types hashable</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/26/strong-types-conversions/" target="_blank" rel="noopener noreferrer">Converting strong units to one another</a></li>
<li><a href="https://www.fluentcpp.com/2017/08/08/metaclasses-ultimate-answer-strong-typing-c/">Metaclasses, the Ultimate Answer to Strong Typing in C++?</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F05%2Fmaking-strong-types-implicitly-convertible%2F&#038;t=Making%20Strong%20Types%20Implicitly%20Convertible&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F05%2Fmaking-strong-types-implicitly-convertible%2F&#038;p&#091;images&#093;&#091;0&#093;=https%3A%2F%2Fi0.wp.com%2Fwww.fluentcpp.com%2Fwp-content%2Fuploads%2F2017%2F10%2Fsrtong-types-implicit-conversions.png%3Ffit%3D1280%252C720%26ssl%3D1&#038;p&#091;title&#093;=Making%20Strong%20Types%20Implicitly%20Convertible" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F05%2Fmaking-strong-types-implicitly-convertible%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2018%2F01%2F05%2Fmaking-strong-types-implicitly-convertible%2F&#038;title=Making%20Strong%20Types%20Implicitly%20Convertible" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2018/01/05/making-strong-types-implicitly-convertible/">Making Strong Types Implicitly Convertible</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1806</post-id>	</item>
		<item>
		<title>Using Strong Types to Return Multiple Values</title>
		<link>https://www.fluentcpp.com/2017/11/10/strong-types-multiple-return-values/</link>
					<comments>https://www.fluentcpp.com/2017/11/10/strong-types-multiple-return-values/#comments</comments>
		
		<dc:creator><![CDATA[Jonathan Boccara]]></dc:creator>
		<pubDate>Fri, 10 Nov 2017 01:00:47 +0000</pubDate>
				<category><![CDATA[Strong types]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[clean code]]></category>
		<category><![CDATA[expressive]]></category>
		<category><![CDATA[interface]]></category>
		<category><![CDATA[multiple return values]]></category>
		<category><![CDATA[strong types]]></category>
		<guid isPermaLink="false">https://www.fluentcpp.com/?p=2533</guid>

					<description><![CDATA[<p>We&#8217;ve seen how strong types helped clarifying function interfaces by being explicit about what input parameters the function expected. Now let&#8217;s examine how strong types help clarifying functions that return several outputs. We&#8217;ll start by describing the various ways to return several outputs from a function in C++, and then see how strong types offer an [&#8230;]</p>
<p>The post <a href="https://www.fluentcpp.com/2017/11/10/strong-types-multiple-return-values/">Using Strong Types to Return Multiple Values</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>We&#8217;ve seen how strong types helped <a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/">clarifying function interfaces</a> by being explicit about what input parameters the function expected. Now let&#8217;s examine how strong types help clarifying functions that return <strong>several outputs</strong>.</p>
<p>We&#8217;ll start by describing the various ways to return several outputs from a function in C++, and then see how <strong>strong types</strong> offer an interesting alternative.</p>
<h3><span style="color: #ff6600;">Multiple return values in C++</span></h3>
<p>Even though, strictly speaking, C++ doesn&#8217;t let functions return several values, some techniques to circumvent this have appeared over time. And some even made their way into becoming native features of the language.</p>
<p>Let&#8217;s take the example of function <code>f</code> that takes an <code>Input</code>, and we would like it to return two outputs: an <code>output1</code> and an <code>output2</code>, which are both of type <code>Output</code>.</p>
<h4><span style="color: #ff6600;">Returning a struct</span></h4>
<p>This is the oldest way, but that still works the best in some cases. It consists in creating a <code>struct</code>, which represents a <a href="https://www.fluentcpp.com/2017/06/13/the-real-difference-between-struct-class/">bundle of data</a>, that contains an <code>Output1</code> and an <code>Output2</code>:</p>
<pre class="lang:c++ decode:true">struct Outputs
{
    Output output1;
    Output output2;

    Outputs(Output const&amp; output1, Output const&amp; output2) : output1(output1), output2(output2){}
};</pre>
<p>In C++03, adding a constructor makes it syntactically easier to set its values:</p>
<pre class="lang:c++ decode:true">Outputs f(Input const&amp; input)
{
    // working out the values
    // of output1 and output2...

    return Outputs(output1, output2);
}</pre>
<p>Note that in C++11 we can omit the <code>struct</code>&#8216;s constructor and use extended initializer lists to fill the <code>struct</code>:</p>
<pre class="lang:c++ mark:6 decode:true">Outputs f(Input const&amp; input)
{
    // working out the values
    // of output1 and output2...

    return {output1, output2};
}</pre>
<p>Anyway, to retrieve the outputs at call site we simply get the members out of the <code>struct</code>:</p>
<pre class="lang:c++ decode:true">auto outputs = f(input);

auto output1 = outputs.output1;
auto output2 = outputs.output2;</pre>
<p>Advantages of the <code>struct</code>:</p>
<ul>
<li>the results coming out of the function appear with their names at call site,</li>
<li>exists in all versions of C++.</li>
</ul>
<p>Drawbacks of the <code>struct</code>:</p>
<ul>
<li>needs to define it (and, in C++03, its constructor) for the purpose of the function.</li>
</ul>
<h4><span style="color: #ff6600;"><code>std::tie</code>ing to a tuple</span></h4>
<p>Another way to output several values is to return a <code>std::tuple</code>, which can be perceived as an on-the-fly <code>struct</code>. So we throw away our <code>Outputs</code> struct, and our function becomes:</p>
<pre class="lang:c++ decode:true">std::tuple&lt;Output, Output&gt; f(Input const&amp; input)
{
    // working out the values
    // of output1 and output2...
    
    return {output1, output2};
}</pre>
<p>At call site there are several ways to retrieve the results. One way is to use the accessors of <code>std::tuple</code>: the <code>std::get</code> template functions:</p>
<pre class="lang:c++ decode:true ">auto output = f(input);

auto output1 = std::get&lt;0&gt;(output);
auto output2 = std::get&lt;1&gt;(output);</pre>
<p>But there is a problem here: we have lost track of the order of the values returned by the function.</p>
<p>We&#8217;re <em>assuming</em> that <code>output1</code> comes first and <code>output2</code> second, but if we get that order wrong (especially in production code where they are hopefully not called output 1 and 2) or if it comes to change, even by mistake, the compiler won&#8217;t stop us.</p>
<p>So we&#8217;re receiving data from a function but can&#8217;t really see that data. It&#8217;s a bit like catching a ball with your eyes closed: you need to be very, very confident towards the person who throws it at you.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-2537" src="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/baseball-1299773_640.png?resize=200%2C400&#038;ssl=1" alt="Multiple return types C++" width="200" height="400" srcset="https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/baseball-1299773_640.png?w=200&amp;ssl=1 200w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/baseball-1299773_640.png?resize=75%2C150&amp;ssl=1 75w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/baseball-1299773_640.png?resize=150%2C300&amp;ssl=1 150w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/baseball-1299773_640.png?resize=16%2C32&amp;ssl=1 16w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/baseball-1299773_640.png?resize=50%2C100&amp;ssl=1 50w, https://i0.wp.com/www.fluentcpp.com/wp-content/uploads/2017/11/baseball-1299773_640.png?resize=101%2C201&amp;ssl=1 101w" sizes="(max-width: 200px) 100vw, 200px" data-recalc-dims="1" /></p>
<p>This problem is mitigated if the outputs are of different types. Indeed, mixing them up would probably lead to a compilation error further down the codeline. But if they are of the same type, like in this example, there is a real risk of mixing them up.</p>
<p>There is another syntax for this technique, using <code>std::tie</code>, that is more pleasant to the eye but has the same risk of mixing up the values:</p>
<pre class="lang:c++ decode:true ">Output output1;
Output output2;

std::tie(output1, output2) = f(input);</pre>
<p><code>std::tie</code> creates a tuple of references bound to <code>output1</code> and <code>output2</code>. So copying the tuple coming out of <code>f</code> into this tuple of references actually copies the value inside the tuple into <code>output1</code> and <code>output2</code>.</p>
<p><code>std::tie</code> also has the drawback of needing the outputs to be instantiated before calling the function. This can be more or less practical depending on the type of the outputs, and adds <strong>visual noise</strong> (er- actually, is there such a thing as visual noise? noise is something you&#8217;re supposed to hear isn&#8217;t it?).</p>
<p>Advantages of <code>std::tie</code>:</p>
<ul>
<li>no need for a <code>struct</code>.</li>
</ul>
<p>Drawbacks of <code>std::tie</code>:</p>
<ul>
<li>the meaning of each returned value is hidden at call site,</li>
<li>needs to instantiate output values before calling the function,</li>
<li>visual noise,</li>
<li>needs C++11 (not everyone has it yet in production).</li>
</ul>
<h4><span style="color: #ff6600;">Structured bindings</span></h4>
<p>Structured bindings are part of the spearhead of C++17 features. They have a lot in common with <code>std::tie</code>, except they&#8217;re easier to use in that they don&#8217;t need the outputs to be previously instantiated:</p>
<pre class="lang:c++ decode:true ">auto [output1, output2] = f(input);</pre>
<p>Which makes for a beautiful syntax. But if the outputs are of the same type, we still have the issue of not knowing if the order of the return values is the right one!</p>
<p>Advantages of structured bindings:</p>
<ul>
<li>no need for a <code>struct</code></li>
<li>no need to instantiate output values before calling the function,</li>
<li>beautiful syntax</li>
</ul>
<p>Drawbacks of structured bindings:</p>
<ul>
<li>the meaning of each returned value is hidden at call site,</li>
<li>needs C++17 (really not everyone has it yet in production)</li>
</ul>
<h3><span style="color: #ff6600;">Multiple Strong return types</span></h3>
<p>This need of disambiguating several return values of the same type sounds very similar to the one of clarifying the meaning of a function&#8217;s parameters, which we <a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/">solved with strong types</a>.</p>
<p>So let&#8217;s use strong types to add specific meaning to each of the return value of our function, by using the <a href="https://github.com/joboccara/NamedType" target="_blank" rel="noopener">NamedType</a> library:</p>
<pre class="lang:c++ decode:true">using Output1 = NamedType&lt;Output, struct Output1Tag&gt;;
using Output2 = NamedType&lt;Output, struct Output2Tag&gt;;
</pre>
<p>Our function can then return those strong types instead of just <code>Output</code>s:</p>
<pre class="lang:c++ decode:true">std::tuple&lt;Output1, Output2&gt; f(Input const&amp; input)
{
    // working out the values
    // of output1 and output2...
    
    return {Output1(output1), Output2(output2)};
}</pre>
<p>Note that the function&#8217;s prototype now shows exactly what outputs the function returns.</p>
<p>At call site, we get an explicit syntax thanks to an overload of <code>std::get</code> that takes a template <strong>type</strong>, and not a number, that works when every type inside the tuple is unique. Which is our case here, because our purpose <em>is</em> to differentiate every value that the function is returning, by using the type system:</p>
<pre class="lang:c++ decode:true">auto outputs = f(input);

auto output1 = std::get&lt;Output1&gt;(outputs);
auto output2 = std::get&lt;Output2&gt;(outputs);
</pre>
<p>Advantages of strong types:</p>
<ul>
<li>the results coming out of the function appear with their names at call site,</li>
<li>the function&#8217;s prototype shows the meaning of each of the returned values,</li>
<li>no need for a <code>struct</code>,</li>
<li>no need to initialize the outputs before calling the function.</li>
</ul>
<p>Drawbacks of strong types:</p>
<ul>
<li>needs to define strong types for the returned types,</li>
<li>not everything in one line at call site,</li>
<li>not standard.</li>
</ul>
<h3><span style="color: #ff6600;">Closing up on <code>struct</code> versus strong types</span></h3>
<p>The solution using strong types has some things in common with the solution that uses <code>struct</code>s. Indeed, both create dedicated types and allow a call site to identify each of the values returned from a function.</p>
<p>What&#8217;s the difference between them? I believe it lies in the function&#8217;s prototype:</p>
<p>With <code>struct</code>s:</p>
<pre class="lang:c++ decode:true ">Outputs f(Input const&amp; input);</pre>
<p>With strong types:</p>
<pre class="lang:c++ decode:true ">std::tuple&lt;Output1, Output2&gt; f(Input const&amp; input);</pre>
<p><strong>The strong types show every returned value, while the <code>struct</code> has one name to designate them collectively.</strong></p>
<p>Which one is better? It depends.</p>
<p>If there <em>is </em>a name that represents the concept of all that assembled data, then it makes sense to use that name with a <code>struct</code>, and even consider if this isn&#8217;t the opportunity to <a href="https://www.fluentcpp.com/2017/06/13/the-real-difference-between-struct-class/">hide them in a <code>class</code></a>.</p>
<p>On the other hand, if the returned values are not related to each other (other than by the fact they come out of our function) it&#8217;s probably better to use strong types and avoid an awkward name to group unrelated concepts.</p>
<p>Also, the strong types could be arguably more reusable than the struct, as another neighbouring function that returns just a subset of them could also use their definition.</p>
<p>Your feedback on all this is welcome. If you want to use strong types, you&#8217;ll find the NamedType library in <a href="https://github.com/joboccara/NamedType">its GitHub repository</a>.</p>
<p>Related articles:</p>
<ul>
<li><a href="https://www.fluentcpp.com/2016/12/05/named-constructors/" target="_blank" rel="noopener noreferrer">Strongly typed constructors</a></li>
<li><a href="https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/" target="_blank" rel="noopener noreferrer">Strong types for strong interfaces</a></li>
<li><a href="https://www.fluentcpp.com/2017/03/06/passing-strong-types-reference-revisited/" target="_blank" rel="noopener noreferrer">Passing strong types by reference</a></li>
<li><a href="https://www.fluentcpp.com/2017/02/20/strong-lambdas-strong-generic-types/" target="_blank" rel="noopener noreferrer">Strong lambdas: strong typing over generic types</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/05/news-strong-types-are-free/">Good news: strong types are (mostly) free in C++</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/23/strong-types-inheriting-functionalities-from-underlying/" target="_blank" rel="noopener noreferrer">Inheriting functionalities from the underlying type</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/30/implementing-a-hash-function-for-strong-types/" target="_blank" rel="noopener noreferrer">Making strong types hashable</a></li>
<li><a href="https://www.fluentcpp.com/2017/05/26/strong-types-conversions/" target="_blank" rel="noopener noreferrer">Converting strong units to one another</a></li>
<li><a href="https://www.fluentcpp.com/2017/08/08/metaclasses-ultimate-answer-strong-typing-c/">Metaclasses, the Ultimate Answer to Strong Typing in C++?</a></li>
<li><a href="https://www.fluentcpp.com/2017/11/07/calling-functions-methods-strong-types/">Calling Functions and Methods on Strong Types</a></li>
</ul>
Don't want to miss out ? <strong>Follow:</strong> &nbsp&nbsp<a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Follow me on twitter" href="https://twitter.com/joboccara" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Follow me on twitter" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Find us on Linkedin" href="https://www.linkedin.com/in/jonathan-boccara-23826921/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Find us on Linkedin" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-follow synved-social-size-48 synved-social-resolution-single synved-social-provider-rss nolightbox" data-provider="rss" target="_blank" rel="nofollow" title="Subscribe to our RSS Feed" href="https://www.fluentcpp.com/feed/" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="rss" title="Subscribe to our RSS Feed" class="synved-share-image synved-social-image synved-social-image-follow" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/rss.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><br/>Share this post!<a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-facebook nolightbox" data-provider="facebook" target="_blank" rel="nofollow" title="Check out this post from Fluent C++" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.fluentcpp.com%2F2017%2F11%2F10%2Fstrong-types-multiple-return-values%2F&#038;t=Using%20Strong%20Types%20to%20Return%20Multiple%20Values&#038;s=100&#038;p&#091;url&#093;=https%3A%2F%2Fwww.fluentcpp.com%2F2017%2F11%2F10%2Fstrong-types-multiple-return-values%2F&#038;p&#091;images&#093;&#091;0&#093;=https%3A%2F%2Fi0.wp.com%2Fwww.fluentcpp.com%2Fwp-content%2Fuploads%2F2017%2F11%2Fstrong-types-multiple-return-values.png%3Ffit%3D1280%252C720%26ssl%3D1&#038;p&#091;title&#093;=Using%20Strong%20Types%20to%20Return%20Multiple%20Values" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="Facebook" title="Check out this post from Fluent C++" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-twitter nolightbox" data-provider="twitter" target="_blank" rel="nofollow" title="Tweet about this" href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.fluentcpp.com%2F2017%2F11%2F10%2Fstrong-types-multiple-return-values%2F&#038;text=Check%20out%20this%20post%20from%20Fluent%20C%2B%2B" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px;margin-right:5px"><img loading="lazy" decoding="async" alt="twitter" title="Tweet about this" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><a class="synved-social-button synved-social-button-share synved-social-size-48 synved-social-resolution-single synved-social-provider-linkedin nolightbox" data-provider="linkedin" target="_blank" rel="nofollow" title="Share on Linkedin" href="https://www.linkedin.com/shareArticle?mini=true&#038;url=https%3A%2F%2Fwww.fluentcpp.com%2F2017%2F11%2F10%2Fstrong-types-multiple-return-values%2F&#038;title=Using%20Strong%20Types%20to%20Return%20Multiple%20Values" style="font-size: 0px;width:48px;height:48px;margin:0;margin-bottom:5px"><img loading="lazy" decoding="async" alt="linkedin" title="Share on Linkedin" class="synved-share-image synved-social-image synved-social-image-share" width="48" height="48" style="display: inline;width:48px;height:48px;margin: 0;padding: 0;border: none;box-shadow: none" src="https://i0.wp.com/www.fluentcpp.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&#038;ssl=1" data-recalc-dims="1" /></a><p>The post <a href="https://www.fluentcpp.com/2017/11/10/strong-types-multiple-return-values/">Using Strong Types to Return Multiple Values</a> appeared first on <a href="https://www.fluentcpp.com">Fluent C++</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.fluentcpp.com/2017/11/10/strong-types-multiple-return-values/feed/</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2533</post-id>	</item>
	</channel>
</rss>
