C++ Template Story So Far(C++11 to C++20)
Tags: cpp, tutorial, programming, codenewbie
Published: 2020-06-14 13:19:52

<!-- wp:paragraph -->
<p>I know, it’s been a while since the last time I published something newbies-friendly on my blog. The main reason is that most of my readers are either experienced devs or from C background having modest C++ encounter. But while programming in C++ you need a completely different mindset as both C &amp; C++ belongs to different programming paradigm. And I always strive to show them a better way of doing things in C++. Anyway, I found the topic which is lengthy, reasonably complex(at least it was for me), newbies-friendly as well as energizing for experienced folks(if <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/21-new-features-of-modern-cpp-to-use-in-your-project/" target="_blank"><span style="color:#9b51e0" class="color">Modern C++</span></a> jargons, rules &amp; features added) i.e. C++ Template. </p>
<!-- /wp:paragraph -->


> /!\\\: Originally published @ [www.vishalchovatiya.com](http://www.vishalchovatiya.com/).

<!-- wp:paragraph -->
<p>I will start with a simple class/function template and as we move along, will increase the complexity. And also cover the advance topics like the <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/variadic-template-cpp-implementing-unsophisticated-tuple/" target="_blank"><span style="color:#9b51e0" class="color">variadic template</span></a>, nested template, CRTP, template vs fold-expression, etc. But, yes! we would not take deeper dive otherwise this would become a book rather than an article.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><em><strong>Note: </strong>I would recommend you to use <a rel="noreferrer noopener" href="https://cppinsights.io/" target="_blank"><span style="color:#9b51e0" class="color">cppinsights</span></a> online tool wherever you feel confused. It helps you to see Template Instances, Template Argument Deduction, etc. Basically, it helps you to see code from the compiler's perspective.</em></p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Terminology/Jargon/Idiom You May Face</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><strong>Template Instantiation</strong>: It is a process of generating a concrete class/struct/union/function out of templated class/struct/union/function for a particular combination of template arguments. For example, if you use <code>vector&lt;int&gt;</code>  &amp; <code>vector&lt;char&gt;</code>, it will create two different concrete classes during compilation. This process of creating concrete classes is known as Template Instantiation.</li><li><strong>Template Instances</strong>: Outcome of Template Instantiation is Template Instances i.e. concrete classes.</li><li><strong>Explicit Template Instantiation</strong>: Usually template instantiation done at the time of object declaration. But you can also force the compiler to instantiate class/struct/union/function with particular type without even creating the object. It may appear in the program anywhere after the template definition, and for a given argument-list. Will see this later in the article.</li><li><strong>Template Argument vs Template Parameter</strong>: In expression <code>template&lt;typename <em>T</em>> void print(<em>T a</em>){ };</code>, <code>T</code> is parameter &amp; when you call <code>print(5);</code>, <code>5</code> which is of type <code>int</code> is template argument. This is a trivial thing for some pips. But not for non-native English speaker or beginners. So, this ambiguity has to be clear.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>C++ Template Types</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>Class Template</h3>
<!-- /wp:heading -->
```C++
template <typename T1, typename T2>
class pair {
public:
    T1  first;
    T2  second;
};

pair<int, char> p1;
pair<float, float> p2;
```

<!-- wp:list -->
<ul><li>The basic idea of a class template is that the template parameter i.e. <code>T1</code> &amp; <code>T2</code> gets substituted by an appropriate deduced type at compile time. The result is that the same class can be reused for multiple types.</li><li>And the user has to specify which type they want to use when an object of the class is declared.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Function Template</h3>
<!-- /wp:heading -->
```C++
template <typename T>
T min(T a, T b) {
    return a < b ? a : b;
}

min<int>(4, 5);              // Case 1 
min<float>(4.1f, 5.1f);      // Case 2
```
<!-- wp:list -->
<ul><li>In both of the above case, the template arguments used to replace the types of the parameters i.e. <code>T</code>.  </li><li>One additional property of template functions (unlike class template till C++17) is that the compiler can infer the template parameters based on the parameters passed to the function. So, passing <code>&lt;int&gt;</code> &amp; <code>&lt;float&gt;</code> after the function name is redundant.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Union Template</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Yes! a union can also be templatized. In fact, the standard library provides some utilities like <a rel="noreferrer noopener" href="https://en.cppreference.com/w/cpp/utility/optional" target="_blank"><code><span style="color:#9b51e0" class="color">std::optional</span></code></a>, <a rel="noreferrer noopener" href="https://en.cppreference.com/w/cpp/utility/variant" target="_blank"><code><span style="color:#9b51e0" class="color">std::variant</span></code></a>, etc. which directly or indirectly uses templatized union.</li></ul>
<!-- /wp:list -->

```c++
template <typename T>
union test {
    uint8_t     ch[sizeof(T)];
    T           variable;
};
```

<!-- wp:list -->
<ul><li>As you can see above,<strong><em> templatized unions are also particularly useful to represent a type simultaneously as a byte array</em></strong>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Variable Template</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Yes! This may a bit socking. But, <strong><em>you can templatise the variable also since C++14</em></strong>.</li></ul>
<!-- /wp:list -->

```c++
template <class T>
constexpr T pi = T(3.1415926535897932385L); // variable template

cout << pi<float> << endl; // 3.14159
cout << pi<int> << endl;   // 3
```


<!-- wp:list -->
<ul><li>Now, you might be wondering that what is the point of the templatizing variable. But, consider the following example:</li></ul>
<!-- /wp:list -->

```c++
template <uint32_t val>
constexpr auto fib = fib<val - 1> + fib<val - 2>;

template <>
constexpr auto fib<0> = 0;

template <>
constexpr auto fib<1> = 1;

cout << fib<10> << endl;    // 55
```
<!-- wp:list -->
<ul><li>Above code gives you 10th Fibonacci term at compile time, without even creating class or function.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>C++ Template Argument</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>Overriding Template Argument Deduction</h3>
<!-- /wp:heading -->

```c++
template <typename T>
T min(T a, T b) {
    cout << typeid(T).name() << endl; // T will be deduce as `int`
    return a < b ? a : b;
}

min<int>(5.5f, 6.6f);     // Implicit conversion happens here
```

<!-- wp:heading {"level":3} -->
<h3>Default Template Arguments</h3>
<!-- /wp:heading -->

```c++
template <class T, size_t N = 10>
struct array {
    T arr[N];
};

array<int> arr;
```

<!-- wp:list -->
<ul><li>Just like in case of the function arguments, template parameters can also have their default values. </li><li>All template parameters with a default value have to be declared at the end of the template parameter list. </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Template Argument Deduction</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>Function Template Argument Deduction</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Function template argument deduction is done by comparing the types of function arguments to function parameters, according to rules in the <a rel="noreferrer noopener" href="https://en.cppreference.com/w/cpp/language/template_argument_deduction" target="_blank"><span style="color:#9b51e0" class="color">Standard</span></a>. Which makes function templates far more usable than they would otherwise be. For example, given a function template like:</li></ul>
<!-- /wp:list -->

```c++
template <typename RanIt> 
void sort(RanIt first, RanIt last){
    // . . .
}
```

<!-- wp:list -->
<ul><li>You can and should sort a <code>std::vector&lt;int&gt;</code> without explicitly specifying that <code>RanIt</code> is <code>std::vector&lt;int&gt;::iterator</code>. When the compiler sees <code>sort(v.begin(), v.end());</code>, it knows what the types of <code>v.begin()</code> and <code>v.end()</code> are, so it can determine what <code>RanIt</code> should be.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Class Template Argument Deduction(CTAD)</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Until C++17, template classes could not apply type deduction in their initialization as template function do. For example</li></ul>
<!-- /wp:list -->

```c++
//...
pair p4{1, 'A'};               // Not OK until C++17: Can't deduce type in initialization 
//...
```

<!-- wp:list -->
<ul><li>But <strong><em>from C++17, the compiler can deduce types in class/struct initialization</em></strong> &amp; this to work, class/struct must have an appropriate constructor. But this limitation is also relaxed in C++20. So technically <strong><em>from C++20, you can construct the object with <a rel="noreferrer noopener" href="https://en.cppreference.com/w/cpp/language/aggregate_initialization" target="_blank"><span style="color:#9b51e0" class="color">aggregate initialization</span></a> &amp; without specifying types explicitly</em></strong>.</li><li>Until C++17, the standard provided some <code>std::make_</code> utility functions to counter such situations as below.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":5} -->
<h5>Inferring Template Argument Through Function Template</h5>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>You might have seen many functions like <code>std::make_pair()</code>, <code>std::make_unique()</code>, <code>std::make_share()</code>, etc. Which can typically &amp; unsophistically implement as:</li></ul>
<!-- /wp:list -->

```c++
template <typename T1, typename T2>
pair<T1, T2> make_pair(T1&& t1, T2&& t2) {
    return {forward<T1>(t1), forward<T2>(t2)};
}
```

<!-- wp:list -->
<ul><li>But have you ever wonder why these helper functions are there in the standard library? How does this even help?</li></ul>
<!-- /wp:list -->

```c++
pair<int, char> p1{1, 'A'};          // Rather using this

auto p2 = make_pair(1, 2);           // Use this instead
auto p3 = make_pair<float>(1, 2.4f); // Or specify types explicitly
```

<!-- wp:list -->
<ul><li>Rather than specifying the arguments explicitly, you can leverage the feature of inferring template argument from function template to construct the object. In the above case, template argument deduction is done by the utility function <code>make_pair</code>. As a result, we have created the object of pair without specifying the type explicitly.</li><li>And as discussed earlier from C++17, you can construct the object without even specifying types explicitly so <code>std::vector v{1,2,3,4};</code> is perfectly valid statement.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Template Argument Forwarding</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>C++ Template Reference Collapsing Rules</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Apart from accepting type &amp; value in the template parameter. You can enable the template to accept both <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/lvalue-rvalue-and-their-references-with-example-in-cpp/" target="_blank"><span style="color:#9b51e0" class="color">lvalue and rvalue references</span></a>. And to do this you need to adhere to the rules of reference collapsing as follows:<ol><li><code>T&amp; &amp;</code>&nbsp;becomes&nbsp;<code>T&amp;</code></li><li><code>T&amp; &amp;&amp;</code>&nbsp;become&nbsp;<code>T&amp;</code></li><li><code>T&amp;&amp; &amp;</code>&nbsp;becomes&nbsp;<code>T&amp;</code></li><li><code>T&amp;&amp; &amp;&amp;</code>&nbsp;becomes&nbsp;<code>T&amp;&amp;</code></li></ol></li></ul>
<!-- /wp:list -->

```c++
template <typename T>
void f(T &&t);
```

<!-- wp:list -->
<ul><li>In the above case, the real type of <code>t</code> depends on the context. For example:</li></ul>
<!-- /wp:list -->

```c++
int x = 0;

f(0); // deduces as rvalue reference i.e. f(int&&)
f(x); // deduces as lvalue reference i.e. f(int&)
```

<!-- wp:list -->
<ul><li>In case of <code>f(0);</code>, <code>0</code> is rvalue of type <code>int</code>, hence <code>T = int&amp;&amp;</code>, thus <code>f(int&amp;&amp; &amp;&amp;t)</code> becomes <code>f(int&amp;&amp; t)</code>.</li><li>In case of <code>f(x);</code>, <code>x</code> is lvalue of type <code>int</code>, hence <code>T = int&amp;</code>, thus <code>f(int&amp; &amp;&amp;t)</code> becomes <code>f(int&amp; t)</code>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Perfect Forwarding | Forwarding Reference | Universal Reference</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>In order to perfectly forward <code>t</code> to another function<a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/lvalue-rvalue-and-their-references-with-example-in-cpp/" target="_blank"><span style="color:#9b51e0" class="color"></span></a>, one must use <code>std::forward</code> as:</li></ul>
<!-- /wp:list -->

```c++
template <typename T>
void func1(T &&t) {
    func2(std::forward<T>(t));  // Forward appropriate lvalue or rvalue reference to another function
}
```

<!-- wp:list -->
<ul><li>Forwarding references can also be used with variadic templates:</li></ul>
<!-- /wp:list -->

```c++
template <typename... Args>
void func1(Args&&... args) {
    func2(std::forward<Args>(args)...);
}
```

<!-- wp:heading {"level":4} -->
<h4>Why Do We Need Forwarding Reference in First Place?</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Answer to this question lies in <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/move-constructor-assignment-operator-with-shared-ptr/" target="_blank"><span style="color:#9b51e0" class="color">move semantics</span></a>. Though, short answer to this question is "To perform copy/move depending upon value category type".</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>C++ Template Category</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>Full Template Specialization</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Template has a facility to define implementation for specific instantiations of a template class/struct/union/function/method.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Function Template Specialization</h4>
<!-- /wp:heading -->

```c++
template <typename T>
T sqrt(T t) { /* Some generic implementation */ }

template<>
int sqrt<int>(int i) { /* Highly optimized integer implementation */ }
```

<!-- wp:list -->
<ul><li>In the above case, a user that writes <code>sqrt(4.0)</code> will get the generic implementation whereas <code>sqrt(4)</code> will get the specialized implementation.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Class Template Specialization</h4>
<!-- /wp:heading -->
```c++
template <typename T>       // Common case
struct Vector {
    void print() {}
};

template <>                 // Special case
struct Vector<bool> {
    void print_bool() {}
};

Vector<int> v1;
v1.print_bool();    // Not OK: Chose common case Vector<T>
v1.print()          // OK

Vector<bool> v2;    // OK : Chose special case Vector<bool>
```

<!-- wp:heading {"level":3} -->
<h3>Partial Template Specialization</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>Partial Class Template Specialization</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>In contrast of a full template specialization, you can also specialise template partially with some of the arguments of existing template fixed. Partial template specialization is only available for template class/structs/union:</li></ul>
<!-- /wp:list -->

```c++
template <typename T1, typename T2>     // Common case
struct Pair {
    T1 first;
    T2 second;

    void print_first() {}
};

template <typename T>    // Partial specialization on first argument as int
struct Pair<int, T> {
    void print() {}
};

// Use case 1 ----------------------------------------------------------
Pair<char, float> p1;    // Chose common case
p1.print_first();        // OK
// p1.print();           // Not OK: p1 is common case & it doesn't have print() method

// Use case 2 ----------------------------------------------------------
Pair<int, float> p2;     // Chose special case
p2.print();              // OK
// p2.print_first();     // Not OK: p2 is special case & it does not have print_first()

// Use case 3 ----------------------------------------------------------
// Pair<int> p3;         // Not OK: Number of argument should be same as Primary template
```
<!-- wp:heading {"level":4} -->
<h4>Partial Function Template Specialization</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><strong><em>You cannot partially specialize method/function</em></strong>. Function templates may only be fully specialized</li></ul>
<!-- /wp:list -->

```c++
template <typename T, typename U>
void foo(T t, U u) {
    cout << "Common case" << endl;
}

// OK.
template <>
void foo<int, int>(int a1, int a2) {
    cout << "Fully specialized case" << endl;
}

// Compilation error: partial function specialization is not allowed.
template <typename U>
void foo<string, U>(string t, U u) {
    cout << "Partial specialized case" << endl;
}

foo(1, 2.1); // Common case
foo(1, 2);   // Fully specialized case
```
<!-- wp:heading {"level":5} -->
<h5>Alternative To Partial Function Template Specialization</h5>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>As I have mentioned earlier, partial specialization of function templates is not allowed. You can use <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/7-advance-cpp-concepts-idiom-examples-you-should-know/" target="_blank"><span style="color:#9b51e0" class="color">SFINAE</span></a> with <code>std::enable_if</code> for work around as follows:</li></ul>
<!-- /wp:list -->

```c++
template <typename T, typename std::enable_if_t<!std::is_pointer<T>::value> * = nullptr>
void func(T val) {  
    cout << "Value" << endl; 
}

template <typename T, typename std::enable_if_t<std::is_pointer<T>::value> * = nullptr>
void func(T val) {  // NOTE: function signature is NOT-MODIFIED
    cout << "Pointer" << endl; 
}

int a = 0;
func(a);
func(&a);
```
<!-- wp:heading {"level":3} -->
<h3>Non-Type Template Parameter</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>As the name suggests, apart from types, you can also declare the template parameter as constant expressions like addresses, <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/lvalue-rvalue-and-their-references-with-example-in-cpp/" target="_blank"><span style="color:#9b51e0" class="color">references</span></a>, integrals, <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/what-exactly-nullptr-is-in-cpp/" target="_blank"><span style="color:#9b51e0" class="color">std::nullptr_t</span></a>, enums, etc.</li><li>Like all other template parameters, non-type template parameters can be explicitly specified, defaulted, or derived implicitly via Template Argument Deduction.</li><li>The <strong><em>more specific use case of a non-type template is passing a plain array into a function without specifying its size explicitly</em></strong>. A more relevant  example of this is <code>std::begin</code> &amp; <code>std::end</code> specialisation for array literal from the standard library:</li></ul>
<!-- /wp:list -->

```c++
template <  class T, 
            size_t size>     // Non Type Template
T* begin(T (&arr)[size]) {   // Array size deduced implicitly
    return arr;
}

int arr[] = {1,2,3,4};
begin(arr);                  // Do not have to pass size explicitly 
```
<!-- wp:list -->
<ul><li>Non-type template parameters are one of the ways to achieve template recurrence &amp; enables <a href="https://en.wikipedia.org/wiki/Template_metaprogramming" target="_blank" rel="noreferrer noopener"><span style="color:#9b51e0" class="color">Template Meta-programming</span></a>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Nested Template: Template Template Parameter</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Sometimes we have to pass templated type into another templated type. And in such case, you not only have to take care of main template type but also a nested template type. Very simple template- template parameter examples is:</li></ul>
<!-- /wp:list -->

```c++
template<   
            template <typename> class C, 
            typename T
        >
void print_container(C<T> &c) {
    // . . .
}

template <typename T>
class My_Type {
    // . . .
};

My_Type<int> t;
print_container(t);
```
<!-- wp:heading {"level":3} -->
<h3>Variadic Template</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>It is often useful to define class/struct/union/function that accepts a variable number and type of arguments. </li><li>If you have already used C you'll know that <code>printf</code> function can accept any number of arguments. Such functions are entirely implemented through macros or <a rel="noreferrer noopener" href="https://stackoverflow.com/questions/3792761/what-is-ellipsis-operator-in-c" target="_blank"><span style="color:#9b51e0" class="color">ellipses operator</span></a>. And because of that it has several disadvantages like <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/cpp-type-casting-with-example-for-c-developers/" target="_blank"><span style="color:#9b51e0" class="color">type-safety</span></a>, cannot accept references as arguments, etc.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Variadic Class Template</h4>
<!-- /wp:heading -->

<!-- wp:heading {"level":5} -->
<h5>Implementing Unsophisticated Tuple Class(&gt;=C++14)</h5>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Since C++11 standard library introduced <code><a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/variadic-template-cpp-implementing-unsophisticated-tuple/" target="_blank"><span style="color:#9b51e0" class="color">std::tuple</span></a></code> class that accept variable data members at compile time using the variadic template. And to understand its working, we will build our own ADT same as <code><code><a href="http://www.vishalchovatiya.com/variadic-template-cpp-implementing-unsophisticated-tuple/" target="_blank" rel="noreferrer noopener"><span style="color:#9b51e0" class="color">std::tuple</span></a></code></code></li><li>The variadic template usually starts with the general (empty) definition, that also serves as the base-case for recursion termination in the later specialisation:</li></ul>
<!-- /wp:list -->
```c++
template <typename... T>
struct Tuple { };
```

<!-- wp:list -->
<ul><li>This already allows us to define an empty structure i.e. <code>Tuple&lt;&gt; object;</code>, albeit that isn't very useful yet. Next comes the recursive case specialisation:</li></ul>
<!-- /wp:list -->

```c++
template<
            typename T, 
            typename... Rest
        >
struct Tuple<T, Rest...> {
    T               first;
    Tuple<Rest...>  rest;

    Tuple(const T& f, const Rest& ... r)
        : first(f)
        , rest(r...) {
    }
};

Tuple<bool> t1(false);                      // Case 1
Tuple<int, char, string> t2(1, 'a', "ABC"); // Case 2
```
<!-- wp:heading {"level":5} -->
<h5>How Does Variadic Class Template Works?</h5>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>To understand variadic class template, consider use case 2 above i.e. <code>Tuple&lt;int, char, string&gt;   t2(1, 'a', "ABC");</code></p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>The declaration first matches against the specialization, yielding a structure with <code>int first;</code> and <code>Tuple&lt;char, string&gt; rest;</code> data members.</li><li>The rest definition again matches with specialization, yielding a structure with <code>char first;</code> and <code>Tuple&lt;string&gt; rest;</code> data members.</li><li>The rest definition again matches this specialization, creating its own <code>string first;</code> and <code>Tuple&lt;&gt; rest;</code> members.</li><li>Finally, this last rest matches against the base-case definition, producing an empty structure.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>You can visualize this as follows:</p>
<!-- /wp:paragraph -->

```c++
Tuple<int, char, string>
-> int first
-> Tuple<char, string> rest
    -> char first
    -> Tuple<string> rest
        -> string first
        -> Tuple<> rest
            -> (empty)
```

<!-- wp:paragraph -->
<p>I have written a separate article on <a href="http://www.vishalchovatiya.com/variadic-template-cpp-implementing-unsophisticated-tuple/" target="_blank" rel="noreferrer noopener"><span style="color:#9b51e0" class="color">Variadic Template C++: Implementing Unsophisticated Tuple</span></a>, if you are interested more in the variadic temple.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Variadic Function Template</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>As we have seen earlier, variadic template starts with empty definition i.e. base case for recursion.</li></ul>
<!-- /wp:list -->

```c++
void print() {}
```

<!-- wp:list -->
<ul><li>Then the recursive case specialisation:</li></ul>
<!-- /wp:list -->

```c++
template<   
            typename First, 
            typename... Rest                    // Template parameter pack
        >     
void print(First first, Rest... rest) {         // Function parameter pack
    cout << first << endl;
    print(rest...);                             // Parameter pack expansion
} 
```
<!-- wp:list -->
<ul><li>This is now sufficient for us to use the print function with variable number and type of arguments. For example:</li></ul>
<!-- /wp:list -->

```c++
print(500, 'a', "ABC");
```

<!-- wp:list -->
<ul><li>You can further optimize the print function with forwarding reference, <code>if constexpr()</code> &amp; <code>sizeof()</code> operator as:</li></ul>
<!-- /wp:list -->

```c++
template<   
            typename First, 
            typename... Rest
        >     
void print(First&& first, Rest&&... rest) {         
    if constexpr(sizeof...(rest) > 0) {             // Size of parameter pack
        cout << first << endl;
        print(std::forward<Rest>(rest)...);         // Forwarding reference
    }
    else {
        cout << first << endl;
    }
} 
```
<!-- wp:heading {"level":5} -->
<h5>How Does Variadic Function Template Works?</h5>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>As you can see we have called print with 3 arguments i.e. <code>print(500, 'a', "ABC");</code></li><li>At the time of compilation compiler instantiate 3 different print function as follows:<ol><li><code>void print(int first, char __rest1, const char* __rest2)</code></li><li><code>void print(char first, const char* __rest1)</code></li><li><code>void print(const char* first)</code></li></ol></li><li>The first print(i.e. accept 3 arguments) will be called which prints the first argument &amp; line <code>print(rest…);</code> expand with second print(i.e. accept 2 arguments). This will go on till argument count reaches to zero.</li><li>That means in each call to print, the number of arguments is reduced by one &amp; the rest of the arguments will be handled by a subsequent instance of print.</li><li>Thus, the number of print instance after compilation is equal to the number of arguments, plus the base case instance of print. Hence, the <strong><em>variadic template also contributes to more code bloating</em></strong>. </li><li>You can get this much better if you put the above example in <a rel="noreferrer noopener" href="https://cppinsights.io/" target="_blank"><span style="color:#9b51e0" class="color">cppinsights</span></a>. And try to understand all the template instances.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Fold Expressions vs Variadic Template</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>As we saw, from C++11, the variadic template is a great addition to C++ Template. But it has nuisance like you need base case &amp; recursive template implementation, etc. </li><li>So, with <strong><em>C++17 standard introduced a new feature named as Fold Expression</em></strong>. Which you can use with parameter pack as follows:</li></ul>
<!-- /wp:list -->

```c++
template <typename... Args>
void print(Args &&... args) {
    (void(cout << std::forward<Args>(args) << endl), ...);
}
```

<!-- wp:list -->
<ul><li>See, no cryptic boilerplate required. Isn't this solution looks neater?</li><li>There are total 3 types of folding: Unary fold, Binary fold &amp; Fold over a comma. Here we have done left folding over a comma. You can read more about Fold Expression <a rel="noreferrer noopener" href="https://www.codingame.com/playgrounds/2205/7-features-of-c17-that-will-simplify-your-code/fold-expressions" target="_blank"><span style="color:#9b51e0" class="color">here</span></a>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Misc</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>C++ Template `typename` vs `class`</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><code>typename</code> and <code>class</code> are interchangeable in most of the cases. </li><li>A general convention is <code>typename</code> used with the concrete type(i.e. in turn, does not depend on further template parameter) while <code>class</code> used with dependent type.</li><li>But there are cases where either <code>typename</code> or <code>class</code> has to be certain.  For example</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>To Refer Dependent Types</h4>
<!-- /wp:heading -->

```c++
template<typename container>
class Example {
    using t1 = typename container::value_type; // value_type depends on template argument of container
    using t2 = std::vector<int>::value_type;   // value_type is concrete type, so doesn't require typename
};
```

<!-- wp:list -->
<ul><li><code>typename</code> is a must while referencing a nested type that depends on template parameter. </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>To Specify Template Template Type</h4>
<!-- /wp:heading -->

```c++
template<
            template <typename, typename> class C, // `class` is must prior to C++17
            typename T, 
            typename Allocator
        >
void print_container(C<T, Allocator> container) {
    for (const T& v : container)
        cout << v << endl;
}

vector<int> v;
print_container(v);
```
<!-- wp:list -->
<ul><li>This is rectified in C++17, So now you can use <code>typename</code> also.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>C++11: Template Type Alias</h3>
<!-- /wp:heading -->

```c++
template<typename T> 
using pointer = T*;

pointer<int> p = new int;   // Equivalent to: int* p = new int;


template <typename T>
using v = vector<T>;

v<int> dynamic_arr;         // Equivalent to: vector<int> dynamic_arr;
```
<!-- wp:list -->
<ul><li><code>typedef</code> will also work fine, but would not encourage you to use. As it isn't part of <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/21-new-features-of-modern-cpp-to-use-in-your-project/" target="_blank"><span style="color:#9b51e0" class="color">Modern C++</span></a>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>C++14/17: Template &amp; auto Keyword</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><strong><em>Since C++14, you can use <code>auto</code> in function argument</em></strong>. It's kind of template shorthand as follows:</li></ul>
<!-- /wp:list -->

```c++
void print(auto &c) { /*. . .*/ }

// Equivalent to

template <typename T>
void print(T &c) { /*. . .*/ }
```
<!-- wp:list -->
<ul><li>Although <strong><em><code>auto</code> in function return-type is supported from C++11</em></strong>. But, you have to mention the trailing return type. Which is rectified in C++14 &amp; now return type is automatically deduced by compiler.</li><li><strong><em>From C++17, you can also use <code>auto</code> in non-type template</em></strong>(I will cover this in later part this article) parameters.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>C++20: Template Lambda Expression </h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>A <a href="http://www.vishalchovatiya.com/learn-lambda-function-in-cpp-with-example/" target="_blank" rel="noreferrer noopener"><span style="color:#9b51e0" class="color">generic lambda expression</span></a> is supported since C++14 which declare parameters as <code>auto</code>. But there was no way to change this template parameter and use real template arguments. For example:</li></ul>
<!-- /wp:list -->

```c++
template <typename T>
void f(std::vector<T>&    vec) {
    //. . .
}
```
<!-- wp:list -->
<ul><li>How do you write the lambda for the above function which takes <code>std::vector</code> of type <code>T</code>? This was the limitation till C++17, but <strong><em>with C++20 it is possible templatized lambda</em></strong> as :</li></ul>
<!-- /wp:list -->

```c++
auto f = []<typename T>(std::vector<T>&  vec) {
    // . . .
};

std::vector<int> v;
f(v);
```
<!-- wp:heading {"level":3} -->
<h3>Explicit Template Instantiation</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>An explicit instantiation creates and declares a concrete class/struct/union/function/variable from a template, without using it just yet. </li><li>Generally, you have to implement the template in header files only. You can not put the implementation/definition of template methods in implementation files(i.e. cpp or .cc). If this seems new to you, then consider following minimalist example:</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p><strong>value.hpp</strong></p>
<!-- /wp:paragraph -->

```c++
#pragma once

template <typename T>
class value {
    T val;
public:
    T get_value();
};
```

<!-- wp:paragraph -->
<p><strong>value.cpp</strong></p>
<!-- /wp:paragraph -->
```c++
#include "value.hpp"

template <typename T>
T value<T>::get_value() { 
    return val; 
}
```

<!-- wp:paragraph -->
<p><strong>main.cpp</strong></p>
<!-- /wp:paragraph -->

```c++
#include "value.hpp"

int main() {
    value<int> v1{9};
    cout << v1.get_value() << endl;
    return 0;
}
```

<!-- wp:list -->
<ul><li>If you compile above code you will get following error:</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock -->
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/tmp/main-4b4bef.o: In function `main':
main.cpp:(.text+0x1e): undefined reference to `value&lt;int>::get_value()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
compiler exit status 1</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>If you do explicit initialization i.e. add <code>template class value&lt;int&gt;;</code> line at the end of <code>value.cpp</code>. Then the compilation gets successful.</li><li>The "template class" command causes the compiler to explicitly instantiate the template class. In the above case, the compiler will stencil out <code>value&lt;int&gt;</code> inside of <code>value.cpp</code>. </li><li>There are other solutions as well. Check out this <a rel="noreferrer noopener" href="https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file" target="_blank"><span style="color:#9b51e0" class="color">StackOverflow link</span></a>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>C++ Template Example Use Cases</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>Curiously Recurring Template Pattern</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/7-advance-cpp-concepts-idiom-examples-you-should-know/#CRTP" target="_blank"><span style="color:#9b51e0" class="color">CRTP</span></a> widely employed for static polymorphism or code reusability without bearing the cost of <a href="http://www.vishalchovatiya.com/part-3-all-about-virtual-keyword-in-c-how-virtual-destructor-works/" target="_blank" rel="noreferrer noopener"><span style="color:#9b51e0" class="color">virtual dispatch mechanism</span></a>. Consider the following code:</li></ul>
<!-- /wp:list -->

```c++
template <typename specific_animal>
struct animal {
    void who() { implementation().who(); }

private:
    specific_animal &implementation() { return *static_cast<specific_animal *>(this); }
};

struct dog : animal<dog> {
    void who() { cout << "dog" << endl; }
};

struct cat : animal<cat> {
    void who() { cout << "cat" << endl; }
};


template <typename specific_animal>
void who_am_i(animal<specific_animal> *animal) {
    animal->who();
}


who_am_i(new dog); // Prints `dog`
who_am_i(new cat); // Prints `cat`
```

<!-- wp:list -->
<ul><li>We have not used <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/part-1-all-about-virtual-keyword-in-cpp-how-virtual-function-works-internally/" target="_blank"><span style="color:#9b51e0" class="color">virtual keyword</span></a> &amp; still achieved the functionality of polymorphism(more-specifically static polymorphism).</li><li>I have written a separate article covering practical examples of Curiously Recurring Template Pattern(CRTP)[TODO].</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Passing `std` Container as C++ Template Argument</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>If&nbsp;you&nbsp;wanted&nbsp;to&nbsp;accept&nbsp;anything&nbsp;and&nbsp;figure&nbsp;it&nbsp;out&nbsp;later,&nbsp;you&nbsp;could&nbsp;write:</li></ul>
<!-- /wp:list -->

```c++
template <typename C>
void print_container(const C &container) {
    for (const auto &v : container)
        cout << v << endl;
}
```

<!-- wp:list -->
<ul><li>This naive way may fail if you pass anything other than standard container as other types may not have <code>begin</code> &amp; <code>end</code> iterator.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Passing std::vector to C++ Template Function</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>Naive Way to Capture Container's Value Type</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>But let say, you want to pass container &amp; want to work with container's storage type also. You can do:</li></ul>
<!-- /wp:list -->

```c++
template<
            typename C, 
            typename T = typename C::value_type
        >
void print_container(const C &container) {
    for (const T &v : container)
        cout << v << endl;
}
```

<!-- wp:list -->
<ul><li>We can provide the second type parameter to our function that uses <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/7-advance-cpp-concepts-idiom-examples-you-should-know/" target="_blank"><span style="color:#9b51e0" class="color">SFINAE</span></a> to verify that the thing is actually a container.</li><li>All standard containers have a member type named <code>value_type</code> which is the type of the thing inside the container. We sniff for that type, and if no such type exists, then <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/7-advance-cpp-concepts-idiom-examples-you-should-know/" target="_blank"><span style="color:#9b51e0" class="color">SFINAE</span></a> kicks in, and that overload is removed from consideration.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Capturing Container's Value Type Explicitly</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>But what if you are passing vector class which doesn't has <code>value_type</code> member? </li><li><code>std::vector</code> is defined as:</li></ul>
<!-- /wp:list -->

```c++
template<
            class T,
            class Allocator = std::allocator<T>
        > 
class vector;
```

<!-- wp:list -->
<ul><li>And you can capture two template arguments of <code>std::vector</code> container explicitly as:</li></ul>
<!-- /wp:list -->

```c++
template<
            template <typename, typename> class C, 
            typename T, 
            typename Allocator
        >
void print_container(C<T, Allocator> container) {
    for (const T& v : container)
        cout << v << endl;
}
```

<!-- wp:list -->
<ul><li>Above template pattern would be same if you want pass container to class/struct/union.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Passing Any Container to C++ Template Function</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>You see if you pass any other containers to the above solution. It won't work. So to make it generic we can use <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/variadic-template-cpp-implementing-unsophisticated-tuple/" target="_blank"><span style="color:#9b51e0" class="color">variadic template</span></a>:</li></ul>
<!-- /wp:list -->

```c++
template<
            template <typename...> class C, 
            typename... Args
        >
void print_container(C<Args...> container) {
    for (const auto &v : container)
        cout << v << endl;
}

vector<int>     v{1, 2, 3, 4}; // takes total 2 template type argument
print_container(v); 

set<int>        s{1, 2, 3, 4}; // takes total 3 template type argument
print_container(s);
```

<!-- wp:heading {"level":3} -->
<h3>Passing Container-of-Container/2D-std::vector as C++ Template Argument</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>This is the case of nested template i.e. template-template parameter. And there are the following solutions:</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Explicit &amp; Complex Solution</h4>
<!-- /wp:heading -->

```c++
template<
            template <typename, typename> class C1,
            template <typename, typename> class C2,
            typename Alloc_C1, typename Alloc_C2,
            typename T
        >
void print_container(const C1<C2<T, Alloc_C2>, Alloc_C1> &container) {
    for (const C2<T, Alloc_C2> &container_in : container)
        for (const T &v : container_in)
            cout << v << endl;
}
```

<!-- wp:list -->
<ul><li>I know this is ugly, but seems more explicit.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Neat Solution</h4>
<!-- /wp:heading -->

```c++
template<   
            typename T1,
            typename T2 = typename T1::value_type,
            typename T3 = typename T2::value_type
        >
void print_container(const T1 &container) {
    for (const T2 &e : container)
        for (const T3 &x : e)
            cout << x << endl;
}
```

<!-- wp:list -->
<ul><li>As seen earlier including <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/7-advance-cpp-concepts-idiom-examples-you-should-know" target="_blank"><span style="color:#9b51e0" class="color">SFINAE</span></a>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Generic Solution: Using Variadic Template</h4>
<!-- /wp:heading -->

```c++
template<
            template <typename...> class C, 
            typename... Args
        >
void print_container(C<Args...> container) {
    for (const auto &container_2nd : container)
        for (const auto &v : container_2nd)
            cout << v << endl;
}
```

<!-- wp:list -->
<ul><li>This is our standard solution using the variadic template will work for a single container or any number of the nested container.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Passing Function to Class Template Argument</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Passing class/struct/union to another class/struct/union as template argument is common thing. But passing function to class/struct/union as template argument is bit rare. But yes it's possible indeed. Consider the <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/decorator-design-pattern-in-modern-cpp/" target="_blank"><span style="color:#9b51e0" class="color">Functional Decorator</span></a> using a <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/variadic-template-cpp-implementing-unsophisticated-tuple/" target="_blank"><span style="color:#9b51e0" class="color">variadic class template</span></a>.</li></ul>
<!-- /wp:list -->

```c++
// Need partial specialization for this to work
template <typename T>
struct Logger;

// Return type and argument list
template <typename R, typename... Args>
struct Logger<R(Args...)> {
    function<R(Args...)>    m_func;
    string                  m_name;
    Logger(function<R(Args...)> f, const string &n) : m_func{f}, m_name{n} { }
 
    R operator()(Args... args) {
        cout << "Entering " << m_name << endl;
        R result = m_func(args...);
        cout << "Exiting " << m_name << endl;
        return result;
    }
};

template <typename R, typename... Args>
auto make_logger(R (*func)(Args...), const string &name) {
    return Logger<R(Args...)>(function<R(Args...)>(func), name);
}

double add(double a, double b) { return a + b; }

int main() {
    auto logged_add = make_logger(add, "Add");
    auto result = logged_add(2, 3);
    return EXIT_SUCCESS;
}
```

<!-- wp:list -->
<ul><li>Above example may seem a bit complex to you at first sight. But if you have a clear understanding of <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/variadic-template-cpp-implementing-unsophisticated-tuple/" target="_blank"><span style="color:#9b51e0" class="color">variadic class temple</span></a> then it won't take more than 30 seconds to understand what's going on here.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Conclusion</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I hope I have covered most of the topics around C++ Template. And yes, this was a very long &amp; intense article. But I bet you that if you do master the C++ template well, it will really give you an edge. And also open a door to sub-world of C++ i.e. template meta-programming.</p>
<!-- /wp:paragraph -->


[Have Any Suggestions, Query or Wants to Say `Hi`? Take the Pressure Off, You Are Just a Click Away.](http://www.vishalchovatiya.com/contact-2/)🖱️