    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: CTAD â€“ What Is This New Acronym All About?</title>
        <link>https://members.accu.org/index.php/articles/2465</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #143 - February 2018</span></div>

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

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

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

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

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

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

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

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

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

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




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;CTAD â€“ What Is This New Acronym All About?</h1>
<p><strong>Author:</strong>&nbsp;Bob Schmidt</p>
<p>
<strong>Date:</strong> 05 February 2018 16:39:05 +00:00 or Mon, 05 February 2018 16:39:05 +00:00</p>
<p><strong>Summary:</strong>&nbsp;What is class template argument deduction? Roger Orr elucidates this new C++17 feature.</p>
<p><strong>Body:</strong>&nbsp;<p>C++17 has now been shipped and the dust is settling. There are a number of new features in the language; one of the last to be added before the final cut goes by the snappy acronym of CTAD. The full name is Class Template Argument Deduction, which may not tell you a great deal more than the acronym does.</p>

<h2>Example with std::pair</h2>

<p>When using class templates youâ€™ve always had to provide the template arguments even when their type was obvious from the use:</p>

<h3>C++98 code</h3>

<pre class="programlisting">
  <span class="dimmed">void test(</span>int<span class="dimmed"> id, </span>std::string<span class="dimmed"> const &amp;name)</span>
  <span class="dimmed">{</span>
<span class="dimmed">    std::pair&lt;</span>int<span class="dimmed">, </span>std::string<span class="dimmed">&gt; p(id, name);</span>
<span class="dimmed">    // ...</span>
  <span class="dimmed">}</span></pre>

<p>Iâ€™ve put the types involved in bold to make the duplication clear. The template arguments have to be provided although itâ€™s pretty clear what they are.</p>

<p>Things changed slightly with the introduction of <code>auto</code> in C++11; it became possible to use the (pre-existing) helper function <code>make_pair</code> to create the variable and so avoid duplication of the types:</p>

<h3>C++11 code</h3>

<pre class="programlisting">
  <span class="dimmed">void test(int id, std::string const &amp;name)</span>
<span class="dimmed">  {</span>
<span class="dimmed">    auto p{</span>std::make_pair<span class="dimmed">(id, name)};</span>
<span class="dimmed">    // ...</span>
 <span class="dimmed"> }</span></pre>

<p>However, this relies on the existence of the <code>make_pair</code> function template so if you wished to provide a similar facility for your own class template you had to ensure a helper function was available. It was simply an idiom to enable using the language rules which do allow template arguments to be deduced when calling <em>function</em> templates.</p>

<p>Class template argument deduction allows us to avoid duplicating type names even when using the constructor syntax:</p>

<h3>C++17 code using CTAD</h3>

<pre class="programlisting">
  <span class="dimmed">void test(</span>int<span class="dimmed"> id, </span>std::string<span class="dimmed"> const &amp;name)</span>
<span class="dimmed">  {</span>
<span class="dimmed">    std::pair p(id, name);</span>
<span class="dimmed">    // ...</span>
 <span class="dimmed"> }</span></pre>

<p>The compiler detects that <code>pair</code> names a class template but no template arguments are supplied and deduces the arguments from the types used in the call of the constructor. (Hence the name of class template argument deduction.)</p>

<p>Use of CTAD makes the class type of the variable <code>p</code> <em>explicit</em>. It removes the need to define a helper function such as <code>make_pair</code> â€“ and it is a better technique as the use of a helper function relies on a naming convention to specify the type to the reader of the code.</p>

<p>As the paper containing the wording [<a href="#[P0091R3]">P0091R3</a>] put it in the summary: â€œIf constructors could deduce their template arguments â€˜like we expect from other functions and methods,â€™ ...â€ This is pretty much what CTAD does.</p>

<p>Since CTAD is now a standard language feature it is available for any existing class templates without any additional changes (see Listing 1).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
// Existing C++ class
template &lt;typename T&gt;
struct point
{
  T x;
  T y;
};

int main()
{
  // New C++17 use
  point pt{0L,0L};
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<h3>Potential problems</h3>

<p>First of all, note that the addition of CTAD to C++17 does not break any <em>existing</em> code as it simply allows some formerly ill-formed code to become valid.</p>

<p>However, before you race to your code-base and remove all explicit specification of class template arguments on variable declarations, there are a few corner cases that might be troublesome.</p>

<p>First of all, the deduction process will only work if there are constructors for the target type that <em>use</em> the template arguments; the process cannot magically guess the type from the arguments. So, for example, CTAD is of no use for the following class as the template argument is not part of the constructor signature:</p>

<pre class="programlisting">
  template &lt;typename T&gt;
  class collection
  {
    public:
    collection(std::size_t size);
    // ...
  };</pre>
  
<p>It can also be a problem when the constructor you desire to invoke uses types derived from the template arguments as there is no way by default to work â€˜backwardsâ€™ to deduce the underlying template argument.</p>

<p>For example, if you wish to construct a <code>vector</code> from a pair of iterators and hence invoke the constructor:</p>

<pre class="programlisting">
  template&lt;class InputIterator&gt;
  vector(InputIterator first, InputIterator last,
  const Allocator&amp; = Allocator());</pre>
  
<p>Doing this directly is problematic as the template argument type for the target collection is <em>implicit</em> in the <code>value_type</code> of the supplied iterators. (Weâ€™ll see below one work around.)</p>

<p>Secondly, if there are several constructors, the constructor you want may not be the one that the deduction will find. This may be a problem if you are trying to use CTAD with classes that were written before C++17 as designing in usable constructors will not have been necessary then. Even small details of the way classes are written can render CTAD inoperable. </p>

<p>Thirdly, in some cases, you <em>do</em> want to use a helper function to create instances of the class for other reasons. One obvious example from the standard library is <code>std::make_shared</code>. As Scott Meyerâ€™s <em>Effective Modern C++</em> puts it in Item 21: â€œPrefer <code>std::make_unique</code> and <code>std::make_shared</code> to direct use of <code>new</code>.â€</p>

<p>Consider the following example:</p>

<pre class="programlisting">
  #include &lt;memory&gt;
  int main()
  {
    std::shared_ptr&lt;int&gt; p(new int(10));
    auto q{std::make_shared&lt;int&gt;(10)};
    std::shared_ptr r(new int(10)); // C++17
  }</pre>
  
<p>The construction of <code>p</code> and <code>r</code> differ in whether the type is explicit or deduced, but in both cases the shared pointer will need to allocate an additional piece of data to manage the shared object. In the construction of <code>q</code>, the target object and the associated management structure can be created using a single allocation.</p>

<h3>Helping choose the right constructor</h3>

<p>The wording for class template argument deduction includes the option of providing <em>explicit</em> deduction guides.</p>

<p>The syntax is similar to that of a function template, except as the declaration is for a constructor-like entity there is no return type.</p>

<p>For example, as we saw above for the case of a vector, the language will not deduce a template argument for the vector constructor taking a pair of iterators. The <em>deduction guide</em> in Listing 2 was added to the standard library [<a href="#[P0433R2]">P0433R2</a>].</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 template&lt;class InputIterator, class Allocator
   = allocator&lt;typename   iterator_traits&lt;InputIterator&gt;::value_type&gt;&gt;
vector(InputIterator, InputIterator, Allocator = Allocator())
-&gt; vector&lt;typename iterator_traits&lt;InputIterator&gt;::value_type, 
     Allocator&gt;;
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>Omitting the (defaulted) allocator argument for ease of understanding we get Listing 3.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template&lt;class InputIterator&gt;
vector(InputIterator, InputIterator)
-&gt; vector&lt;typename iterator_traits&lt;InputIterator&gt;::value_type&gt;;
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<p>This instructs the compiler when it sees a constructor call taking a pair of iterators, to construct a vector using the value_type of the iterator type, such as:</p>

<pre class="programlisting">
  void foo(std::set&lt;int&gt; const &amp;c)
  {
    std::vector v(c.begin(), c.end());
    // ...</pre>

<p>and <code>v</code> will be deduced as <code>std::vector&lt;int&gt;</code>, as expected.</p>

<p>(Note that this is more restrictive than the range of options available using the full syntax, as in this case the vector to be constructed can, in general, be of <em>any</em> type that <code>int</code> can be converted to.)</p>

<h3>Helping prevent inappropriate choices</h3>

<p>There are times when you may with to prevent use of CTAD for a class, for example when the constructor chosen is unlikely to be the one that the user expected.</p>

<p>One way to remove the possibility of using class template argument deduction is to change the constructor to take a type <em>derived</em> from the template arguments (see Listing 4).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template &lt;typename T&gt;
struct no_ctad { using type_t = T; };

template &lt;typename T&gt;
using no_ctad_t = typename no_ctad&lt;T&gt;::type_t;

template &lt;typename T&gt;
class test
{
public:
  test(no_ctad_t&lt;T&gt;);
};

int main()
{
   test t(1); // Error
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>

<p>The compiler is not allowed to â€˜work upstreamâ€™ and deduce a possible value of <code>T</code> (i.e. <code>int</code>) that would make <code>no_ctad_t&lt;T&gt;</code> match the supplied argument. This is the same rule that already applies to regular template argument deduction on function calls.</p>

<p>(Note: Timur Doumler is proposing standardising a class similar to <code>no_ctad</code> â€“ this use case is one of the motivating examples)</p>

<p>A second way, detailed in [<a href="#[P0091R4]">P0091R4</a>], would be to extend the usage of deleted functions (<code>&quot;=delete&quot;</code>) to also allow for deleted deduction guides. This has not yet been adopted into the working paper, but approval for this direction has been given by the Evolution working group.</p>

<h2>Primary template and explicit specialisations</h2>

<p>Class template argument deduction applies to the primary template. If an explicit specialization of this template defines different constructors these will <em>not</em> be found by CTAD. See Listing 5, for example.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template &lt;typename T&gt;
class myclass {};

template &lt;&gt;
class myclass&lt;int&gt;
{
public:
   myclass(int);
   // ...
};

int main()
{
   myclass m(1); // Error: primary template only
                 // has a default ctor
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 5</td>
	</tr>
</table>

<h2>Future directions</h2>

<p>When CTAD was first proposed it was suggested that you could provide <em>some</em> template arguments and deduce the others. This is not currently in the working paper as it was felt safest to start with an â€˜all or nothingâ€™ approach where there are fewer opportunities for confusion or ambiguity and to consider a future extension if one is provided.</p>

<h3>Compiler support</h3>

<p>CTAD is part of C++17 and so will eventually be provided by any compiler offering support for the current C++ standard.</p>

<p>However, at the time of writing (end of 2017) not all the mainstream compilers have yet released versions implementing this part of the language.</p>

<p>So for example while both gcc 7.1 and clang 5.0 support the feature, the latest version of MSVC does not [<a href="#[C++17 progress]">C++17 progress</a>], nor does it appear that Intelâ€™s compiler does. The status may of course have changed by the time you read this article.</p>

<p>So your ability to make use of class template argument deduction in your code will depend on which compilers â€“ and which version of those compilers â€“ your project is targetting.</p>

<h2>Summary</h2>

<p>Class template argument deduction does not let you write any new code that you couldnâ€™t already write, albeit with slightly more syntax.</p>

<p>However, the reduction in syntax does reduce the burden for the reader of the code and also ensures that, since the target types are deduced, the code automatically changes if the type of the supplied arguments change.</p>

<p>I consider CTAD a useful technique for reducing cognitive overhead and improving readability.</p>

<h2>References</h2>

<p class="bibliomixed"><a id="[C++17 progress]"></a>[C++17 progress] <a href="https://blogs.msdn.microsoft.com/vcblog/2017/12/19/c17-progress-in-vs-2017-15-5-and-15-6/">https://blogs.msdn.microsoft.com/vcblog/2017/12/19/c17-progress-in-vs-2017-15-5-and-15-6/</a></p>

<p class="bibliomixed"><a id="[P0091R3]"></a>[P0091R3] <a href="http://wg21.link/p0091r3">http://wg21.link/p0091r3</a> </p>

<p class="bibliomixed"><a id="[P0091R4]"></a>[P0091R4] <a href="http://wg21.link/p0091r4">http://wg21.link/p0091r4</a></p>

<p class="bibliomixed"><a id="[P0433R2]"></a>[P0433R2] <a href="http://wg21.link/p0433r2">http://wg21.link/p0433r2</a></p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
