﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<style type="text/css">
.comment { color: #808080; font-style: italic; }
.pre { color: #000099; }
.string { color: #009900; }
.char { color: #009900; }
.float { color: #996600; }
.int { color: #999900; }
.bool { color: #000000; font-weight: bold; }
.type { color: #FF6633; }
.flow { color: #FF0000; }
.keyword { color: #990000; }
.operator { color: #663300; font-weight: bold; }
.operator { color: #663300; font-weight: bold; }
pre.code {
    border: 2px solid #666;
    background-color: #F4F4F4;
    padding-left: 10px;
    padding-top: 0px;
}
code {
    border: 2px solid #d0d0d0;
    background-color: LightYellow;
    padding: 2px;
    padding-left: 10px;
    display:table;
    white-space:pre;
    margin:2px;
    margin-bottom:10px;
}
dt
{
    font-weight: bold;
}
    
.ins {
    background-color:#A0FFA0;
}

.del {
    background-color:#FFA0A0;
    text-decoration:line-through
}    
</style>
    <title>Template Tidbits</title>
</head>
<body>

    <p>
        N3405=12-0095<br />
    2012-09-22<br />
    Mike Spertus, 
    Symantec<br />
    <a href="mailto:mike_spertus@symantec.com"><tt>mike_spertus@symantec.com</tt></a><br />
    Subsumes <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2332.pdf">N2332=07-0192</a></p>
    <h1>
        Template Tidbits</h1>
    <p>
        This paper collects several tweaks to C++&#39; template mechanism.</p>
        <ul>
            <li><a href="#T_for_two"><tt>T</tt> for two</a></li>
            <li><a href="#deduction">Template argument deduction for constructors</a></li>
            <li><a href="#scope">Parameter pack scope</a></li>
            <li><a href="#virtual">Virtual (fully-specialized) template methods</a></li>
        </ul>
    <h2>
        <a name="T_for_two"></a><tt>T</tt> for <tt>t</tt>wo</h2>
    <p>
        The motivating example is a putative
        reflection type trait giving properties of a class member.</p>
<code>struct A {
  void f(int i);
  double g(size_t s);
};
<span class="comment">/* ... */</span>
cout &lt;&lt; describe&lt;&amp;A::f&gt;::name; <span class="comment">  // Prints "f"</span>
cout &lt;&lt; describe&lt;&amp;A::g&gt;::arity; <span class="comment">  // prints 1</span> </code>
The question is "what should the declaration of <tt>describe</tt> look like?" Since it takes 
    a non-type template parameter, we need to specify the type of the parameter 
    using the familiar (100k hits on Google) &ldquo;<tt style="white-space:nowrap">template&lt;class T, T t&gt;</tt>&rdquo; idiom
<code>template&lt;typename T, T t&gt; struct describe;</code>
<p>Of course, we would then need to 
    change are original code to call <tt>describe</tt> with the uglier
<code>cout &lt;&lt; describe&lt;decltype(&amp;A::f), &amp;A::f&gt;::name; <span class="comment">  // Prints "f"</span>
cout &lt;&lt; describe&lt;decltype(&amp;A::g), &amp;A::g&gt;::arity; <span class="comment">  // prints 1</span> </code>
Significantly uglier examples can be constructed with variadics.</p>
    Our key idea is that passing the type of the second template parameter is 
    (nearly always) redundant information because it can be inferred using ordinary 
    type deduction from the second type parameter. With that in mind, we propose 
    allowing <tt>describe</tt> to be declared as follows.
<code>template&lt;typename T t&gt; struct describe;
<span class="comment">/* ... */</span>
cout &lt;&lt; describe&lt;&amp;A::f&gt;::name;   <span class="comment">// OK. T is void(A::*)(int)</span>
cout &lt;&lt; describe&lt;&amp;A::g&gt;::arity;  <span class="comment">// OK. T is double(A::*)(size_t)</span> </code>
Handling variadics works as follows:
<code><span class="comment">// Takes arbitrary list of non-type parameters</span>
template&lt;typename... T... t&gt; struct A {<span class="comment">/* ... */</span>};  
A&lt;7, "foo"&gt; a;  <span class="comment">// T is the parameter pack &lt;int, const char[4]&gt;</span></code>

Note that this proposal works for functions as well.
<code>template&lt;typename T t&gt;
T f();
int i = f&lt;7&gt;()<span class="comment"> // OK, T is int</span>
</code>
<h3>Extended version</h3>
As a more detailed example, we would like to have the same ability to
deduce template parameters from values as we do with partial specialization
of classes. This allows us to do provide useful and uniform facilities like
writing a wrapper function for a given function that has 
the same signature as the function it wraps, with no runtime overhead.
<p>As a motivating example,    I&#39;ve found code like the following to be all too familiar in projects I have 
    been involved in.
<code>log &lt;&lt; "Getting ready to call Order::execute on " &lt;&lt; *this &lt;&lt; with arguments " 
    &lt;&lt; a1 &lt;&lt; ", " &lt;&lt; a2 &lt;&lt; endl;
auto result = execute(a1, a2);
log &lt;&lt; "Order::execute returned " &lt;&lt; result &lt;&lt; endl;
 </code></p>
 Here we define a wrapper function that can log calls to general methods at a callsite.
 (Note that this also leverages the putative <tt>describes</tt> template from above)
 <code><span class="comment">// Convenience function to variadically print to a stream</span>
template&lt;typename T, typename... Ts&gt;
void printArgs(ostream &amp;os, T&amp;&amp; t, Ts&amp;&amp;... ts) {
  os &lt;&lt; t &lt;&lt; ", ";
  printArgs(os, forward&lt;Ts&gt;(ts)...);
};
void printArgs(ostream &amp;os) {}

<span class="comment">// Write the wrapper once and for all</span>
template&lt;typename Result(class T::*m)(typename... Args)&gt;
Result wrap_and_log ()(T *t, Args&amp;&amp;... args) {
  log &lt;&lt; "Getting ready to call " &lt;&lt; describe&lt;m&gt;::name &lt;&lt; " with arguments ";
  printArgs(log, args...);
  Result result = t-&gt;*m(forward&lt;Args&gt;(args)...);
  log &lt;&lt; describe&lt;m&gt;::name &lt;&lt; " returned " &lt;&lt; result;
  return result;
}
<span class="comment">/* ... */</span>
<span class="comment">// Now that's out of the way, we can replace the above example by (less than) one line</span>
auto result = wrap_and_log(&amp;A::f, this, a1, a2);
</code>
    &nbsp;<h2>
        <a name="deduction"></a>Template argument deduction for constructors</h2>
    <p>
        This is a revival of
        <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2332.pdf">N2332=07-0192</a>, 
        which was deferred to the current standards cycle.</p>
    <p>
        According to the standard, template argument deduction may be done for 
        functions. However, many important C++ idioms, such as <tt>for_each</tt> loops 
        and factory patterns, use class constructors as if they were functions. 
        Unfortunately, template argument deduction is not done in that case. This makes 
        such constructs substantially more difficult than they need to be, and also 
        makes functors less function-like than they need to be. Furthermore, it is 
        weirdly inconsistent for constructors to participate in overload resolution but 
        not in template argument deduction.</p>
    <p>
        This is often handled by the awkward <tt>make_*</tt> idiom for constructing template 
        classes. For example, whereas <tt style="white-space:nowrap">new X(<span class="comment">/* ... */</span>)</tt> 
        suffices to create non-template classes, I often need to say something like <tt style="white-space:nowrap">make_tuple(7, bind(std::multiplies&lt;int&gt;, _1, _1))</tt>.&nbsp; 
        Does this extra delegation to the <tt>make_tuple</tt> function serve any necessary purpose? 
        Well, I can always create a (simple) tuple like <tt style="white-space:nowrap">new tuple&lt;int, double&gt;(5, 3.2)</tt>,
        but the template arguments are redundant because they are implied by the arguments (this is why <tt>make_tuple</tt> exists!).
        Really, it would be much better if you could just say <tt style="white-space:nowrap">new tuple(5, 3.2)</tt>, which is what
        we are proposing.</p>
    <p>Another problem with the <tt>make_*</tt> idiom is that it can't be used in all of the ways constructors are used, so 
        code like the following is awkward. 
<code>using namespace std;
template&lt;class Func&gt;
class Foo() { 
public: 
    Foo(Func f) : func(f) {} 
    void operator()(int i) { 
      os &lt;&lt; "Calling with " &lt;&lt; i &lt;&lt; endl;
      f(i); 
    } 
private: 
    Func func; 
}; 

void bar(vector&lt;int&gt; vi) { 
    int a;
    for_each(vi.begin(), vi.end(), Foo&lt;<span class="comment">???</span>&gt;([&amp;](int i) { a += i*i; })); 
}</code>
If we allowed the compiler to deduce the template arguments, we could simple write the <tt>for_each</tt> loop
as<code>for_each(vi.begin(), vi.end(), Foo([&amp;](int i) { a += i*i; }</code></p>
<p>What are the limits on this deduction? All of the classes
non-defaulted template parameters need to be directly included in the function arguments. This is not so bad, because template 
    parameter deduction for ordinary functions has the exact same limitation, so we 
    are nothing if not consistent. Neither
<code>template&lt;class T&gt;
struct F {
  F(typename T::x);
};
auto a = F(x);<span class="comment">// Error: Cannot deduce <tt>T</tt></span></code>
nor
<code>template&lt;class T&gt;
T F(typename T::x);
auto a = F(x);<span class="comment">// Error: Cannot deduce <tt>T</tt></span></code>
compile.</p>
        <a name="scope"></a><h2>Parameter pack scope</h2>
        This one is truly a tidbit. We propose that the following be well-formed.
<code>template&lt;typename... T, void (*)(T...), T... t&gt;
struct S {<span class="comment"> /* ... */</span>};
void f(int, double);
S&lt;int, double, f, 5, 4.1&gt; s;</code>
Currently, this doesn't work because all template parameters
are absorbed by <tt>T</tt>, even though they are not types. 
This proposal is simply that a non-type passed as a template parameter
terminates the scope of a <tt>typename...</tt>. Note that
examples of this sort come up when trying to pass a function
as a template parameter (Although the <tt>T</tt> for two tidbit
helps here also, neither moots the other). Likewise, it is
not unreasonable to desire passing some types as parameters
and then passing non-type template parameters of the given types.
<h2><a name="virtual"></a>Virtual (fully-specialized) template methods</h2>
    &ldquo;Everybody knows&rdquo; that template methods cannot be virtual because vtable entries need 
    to point at real methods, not templates. However, a full specialization of a 
    template method is an actual method in itself, and could conceivably be 
    permitted to be virtual. This is interesting, but why would anyone care? Well, 
    in Andrei Alexandrescu&#39;s seminal book
    <em>Modern C++ Design</em>, section 3.1 on&quot;The need for typelists&quot; discusses a 
    scenario (the Factory pattern) and lists two main obstacles (emphasis mine).
<blockquote>However, we cannot fulfill these needs. First, the typedef for WidgetFactory above is not possible because templates cannot have a variable number of parameters.
 Second, the template syntax <tt>Create&lt;Xxx&lt;()</tt> is not legal <em>because virtual functions cannot be templates.</em></blockquote>
 He then uses some very ugly (but necessary) techniques to simulate virtual fully-specialized template functions to create the factory with code
 that (leveraging variadics) is more or less equivalent to the following (see Chapter 9 for
 explanation of these techniques)
 <code>template&lt;typename T&gt; struct Type2Type {};
 
template&lt;typename... Ts&gt; struct AbstractFactoryHelper;

template&lt;&gt; struct AbstractFactoryHelper&lt;&gt; {};

template&lt;typename T, typename... Ts&gt;
struct AbstractFactoryHelper&lt;T, Ts...&gt; : public AbstractFactoryHelper&lt;Ts...&gt; {
   virtual T *doCreate(Type2Type&lt;T&gt;) = 0;
};

template&lt;typename... Ts&gt;
struct AbstractFactory : public AbstractFactoryHelper&lt;Ts...&gt; {
  template&lt;typename T&gt;
  T *create() {
    return doCreate(Type2Type&lt;T&gt;());
  }
}</code>
    If we allowed fully-specialized methods to be virtual, not only is the code 
    shorter, it is clearer and more natural with fewer guru techniques (we do not want to pursue 
    conciseness for its own sake!).
<code>template&lt;typename... Ts&gt;struct AbstractFactoryHelper;

template&lt;&gt; struct AbstractFactoryHelper&lt;&gt; {};

template&lt;typename T, typename... Ts&gt;
struct AbstractFactoryHelper&lt;T, Ts...&gt; : public AbstractFactoryHelper&lt;Ts...&gt; {
   template&lt;&gt; virtual T *create&lt;T&gt;() = 0;
};

template&lt;typename... Ts&gt;
struct AbstractFactory : public AbstractFactoryHelper&lt;Ts...&gt; {
  template&lt;typename T&gt; T *create();
}</code>
One requirement is likely to be that the specializations are visible in all
translation units, but that is satisfied in the motivating examples
and can be viewed as a (possibly extended) ODR requirement. The warning 
in &sect;14.7.3p8 of the standard saying
<blockquote>When writing a specialization, be careful
about its location; or to make it compile will be such a trial as to kindle its self-immolation.</blockquote>
still applies, but we've already accepted the consequences of having a language with specializations,
let's maximize their benefit.
</body>
</html>
