<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ali aji on Medium]]></title>
        <description><![CDATA[Stories by Ali aji on Medium]]></description>
        <link>https://medium.com/@alishoo108?source=rss-8efa235e87a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*z-PgwD7rse2sJOkG</url>
            <title>Stories by Ali aji on Medium</title>
            <link>https://medium.com/@alishoo108?source=rss-8efa235e87a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 20:38:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alishoo108/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Template Specialization in C++]]></title>
            <link>https://medium.com/@alishoo108/template-specialization-in-c-c8211bd99301?source=rss-8efa235e87a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8211bd99301</guid>
            <category><![CDATA[template]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[generic-programming]]></category>
            <dc:creator><![CDATA[Ali aji]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 07:51:24 GMT</pubDate>
            <atom:updated>2023-07-15T07:24:49.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_nE1B0x_PZbEytSDPLBLQ.png" /></figure><p>Hello all, in a previous article we talked about templates and generic programming in C++, if you want you can check it out <a href="https://medium.com/@alishoo108/exploring-the-templates-in-c-71d765e976de">here</a>. We mentioned template specialization in a few words and an example but now I would like to talk more about it, I will also introduce Template type deduction for you.</p><p>Template specialization is the process of providing explicit implementations for templates to handle specific types differently. It allows us to override the default behavior of a template for a particular type or a subset of types. In C++, we have primary templates, which provide a generic implementation, and specialized templates, which provide custom implementations for specific types.</p><p>The syntax for template specialization involves declaring a specialized template for a specific type by using the template &lt;&gt; syntax before the definition of the template. For example:</p><pre>template &lt;typename T&gt;<br>void printValue(T value) {<br>    // Generic implementation for all types<br>    std::cout &lt;&lt; &quot;print generic value: &quot; &lt;&lt; value &lt;&lt; std::endl;<br>}<br><br>template &lt;&gt;<br>void printValue&lt;int&gt;(int value) {<br>    // Specialized implementation for integers<br>    std::cout &lt;&lt; &quot;print integer value: &quot; &lt;&lt; value &lt;&lt; std::endl;<br>}</pre><h4><strong>Explicit Specialization</strong></h4><p>Explicit specialization is used when we want to provide a custom implementation for a specific type. It allows us to override the default behavior of a template for that type. We can explicitly specialize functions, classes, and member functions.</p><p>For example, consider a template function that calculates the square of a number:</p><pre>template &lt;typename T&gt;<br>T Square(T value) {<br>    return value * value;<br>}<br><br>// Explicit specialization for &#39;int&#39;<br>template &lt;&gt;<br>int Square&lt;int&gt;(int value) {<br>    return value * value * value;<br>}</pre><p>Now, let’s call the Square function for different types:</p><pre>int result1 = Square(5);      // Explicit specialization for &#39;int&#39; is used: 5 * 5 * 5 = 125<br>double result2 = Square(3.5); // Generic implementation is used: 3.5 * 3.5 = 12.25</pre><p>In this example, when calling Square(5), the explicit specialization for int is used, resulting in a value of 125. However, when calling Square(3.5), the generic implementation is used since there is no specialization for double, resulting in a value of 12.25.</p><h4>Partial Specialization</h4><p>Partial specialization allows customization of templates based on a subset of types. It enables us to provide different implementations for specific patterns of types rather than individual types.</p><p>Partial specialization syntax differs for class templates and function templates. For class templates, we can partially specialize the template based on specific type patterns. For example:</p><pre>template &lt;typename T, typename U&gt;<br>class Pair {<br>    // Generic implementation<br>};<br><br>// Partial specialization for Pair when both types are the same<br>template &lt;typename T&gt;<br>class Pair&lt;T, T&gt; {<br>    // Specialized implementation for Pair with same type<br>};</pre><p>Similarly, partial specialization can be applied to function templates by using template parameters in the specialization.</p><p>Now, let’s create instances of the Pair class and call the Print function:</p><pre>Pair&lt;int, double&gt; pair1(3, 4.5);<br>pair1.Print(); // Generic implementation is used: (3, 4.5)<br><br>Pair&lt;int, int&gt; pair2(5);<br>pair2.Print(); // Partial specialization for integers is used: [5, 5]</pre><p>In this example, pair1 is an instance of Pair&lt;int, double&gt;, and the generic implementation is used for Print(), resulting in the output &quot;(3, 4.5)&quot;. However, pair2 is an instance of Pair&lt;int, int&gt;, and the partial specialization for the same type is used, resulting in the output &quot;[5, 5]&quot;.</p><h4>Non-Type Template Parameters</h4><p>Template specialization is not limited to types. We can also specialize templates based on non-type parameters, such as integers or enumerations. This enables us to customize templates based on specific values.</p><p>Non-type template parameters must be known at compile-time. They can be used as arguments in template specialization to differentiate between different use cases.</p><p>For example, consider a template class Array that takes a type and a size as template arguments:</p><pre>template &lt;typename T, int Size&gt;<br>class Array {<br>    // Generic implementation for an array of size &#39;Size&#39;<br>};<br><br>// Specialization for Array with size 5<br>template &lt;typename T&gt;<br>class Array&lt;T, 5&gt; {<br>    // Specialized implementation for an array of size 5<br>};</pre><p>Now, let’s create instances of the Array class and call the Fill and Print functions:</p><pre>Array&lt;int, 3&gt; arr1;<br>arr1.Fill(10);<br>arr1.Print(); // Generic implementation is used: 10 10 10<br><br>Array&lt;int, 5&gt; arr2;<br>arr2.Fill(7);<br>arr2.Print(); // Specialization for size 5 is used: 7 7 7 7 7</pre><p>In this example, arr1 is an instance of Array&lt;int, 3&gt;, and the generic implementation is used for Fill() and Print(), resulting in the output &quot;10 10 10&quot;. However, arr2 is an instance of Array&lt;int, 5&gt;, and the specialization for size 5 is used, resulting in the output &quot;7 7 7 7 7&quot;.</p><h4>Template Specialization vs. Overloading</h4><p>Template specialization and function overloading are related concepts in C++. Both techniques allow us to provide different implementations for different types. However, there are key differences between them.</p><p>Template specialization is resolved at compile-time, whereas function overloading is resolved at runtime. Template specialization allows us to customize the behavior of a template based on types or values known at compile-time, providing more flexibility and potentially optimizing code execution.</p><p>Function overloading, on the other hand, allows us to provide different implementations of functions based on the number and types of arguments. Overloading is useful when the behavior of the function depends on the runtime values passed to it.</p><p>It’s important to choose the right technique based on the specific requirements of your code.</p><h4>Template type deduction</h4><p>Template type deduction is the process by which the compiler determines the appropriate template arguments based on the function arguments or the context in which the template is used.</p><p>I will give a small introduction about it, and I really recommend you to check Item1 in <strong>Scott Meyers</strong> book, <strong>Effective Modern c++.</strong></p><p>When a template function is called without explicitly specifying the template arguments, the compiler uses template type deduction to infer the types based on the function arguments. This allows us to write generic code that can work with different types without explicitly specifying them.</p><p>For example, consider a template function Max that returns the maximum value between two arguments:</p><pre>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    return (a &gt; b) ? a : b;<br>}<br><br>int main() {<br>    int maxInt = Max(5, 10);             // Type deduction: T is deduced as int<br>    double maxDouble = Max(3.5, 7.2);    // Type deduction: T is deduced as double<br><br>    return 0;<br>}</pre><p>In this example, the Max function is called without explicitly specifying the template argument. The compiler performs type deduction based on the argument types and deduces T as int for the first call and double for the second call. This allows the Max function to work with different types seamlessly.</p><p>Template type deduction is essential in generic programming as it eliminates the need for manually specifying template arguments in many cases. It allows us to write generic code that can adapt to different types, making our code more flexible and reusable.</p><p>While template specialization focuses on providing custom implementations for specific types or situations, template type deduction plays a crucial role in enabling generic programming by inferring the template arguments based on the context or function arguments</p><p>Understanding and utilizing template specialization effectively expands the capabilities of C++ and enables us to write flexible and customizable code.</p><p>Through explicit specialization, partial specialization, and specialization based on non-type template parameters, we gain fine-grained control over our templates. By choosing the appropriate technique and following best practices, we can leverage template specialization to create efficient and maintainable code.</p><p>So go ahead, explore the world of template specialization in C++, and unlock the full potential of generic programming in your projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8211bd99301" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Templates in C++]]></title>
            <link>https://medium.com/@alishoo108/exploring-the-templates-in-c-71d765e976de?source=rss-8efa235e87a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/71d765e976de</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[metaprogramming]]></category>
            <category><![CDATA[template]]></category>
            <dc:creator><![CDATA[Ali aji]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 15:03:13 GMT</pubDate>
            <atom:updated>2023-06-26T09:28:37.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*Lrwht1Cmz3GGttbMB3Re3A.png" /></figure><p>C++ is renowned for its flexibility and performance and at the heart of its power lies templates. Templates allow us to write generic code that can handle different data types, providing an unparalleled level of flexibility, code reuse, and efficiency. In this article, we will embark on a comprehensive exploration of templates in C++, diving into their various applications, benefits, and advanced techniques.</p><h4><strong>Understanding Templates:</strong></h4><p>Templates in C++ enable generic programming, empowering us to create algorithms, containers, and functions that operate independently of specific data types. The concept revolves around parameterizing types and algorithms, freeing us from writing repetitive code for each data type.</p><h4><strong>Advantages of Templates:</strong></h4><ul><li>Code Reusability: Templates eliminate the need for duplicated code by allowing us to write functions and classes that work with multiple data types. This results in cleaner, more maintainable code.</li><li>Flexibility: Templates allow us to create algorithms and data structures that can adapt to various data types, enabling us to write flexible and versatile code.</li><li>Type Safety: Templates provide compile-time type checking, ensuring that type-related errors are caught before runtime, leading to more robust and reliable code.</li><li>Performance: Templates support compile-time polymorphism, allowing the compiler to generate specialized code for each specific data type used. This results in efficient execution and avoids the overhead of runtime polymorphism.</li></ul><h4><strong>Using Templates in Practice:</strong></h4><p>In the earlier versions of C++, templates were introduced, laying the foundation for generic programming. Let’s look at some key features and examples:</p><p><strong>Template Functions:</strong></p><pre>template &lt;typename T&gt;<br>T maximum(T a, T b) {<br>    return (a &gt; b) ? a : b;<br>}<br><br>int intResult = maximum&lt;int&gt;(5, 10);<br>double doubleResult = maximum&lt;double&gt;(4.9, 6.8);</pre><p><strong>Template Classes:</strong></p><pre>template &lt;typename T&gt;<br>class MyVector {<br>    // Implementation details<br>};<br><br>MyVector&lt;int&gt; myIntVector;<br>MyVector&lt;double&gt; myDoubleVector;</pre><p><strong>Template Specialization:</strong></p><p>Template specialization is a feature in C++ that allows you to provide a specialized implementation of a template for a specific data type or set of data types. It allows you to tailor the behavior of a template for specific cases, providing a more specific implementation and optimizing the code for specific data types than the generic template.</p><pre>template &lt;typename T&gt;<br>void printValue(T value) {<br>    // Generic implementation for all types<br>    std::cout &lt;&lt; &quot;print generic value: &quot; &lt;&lt; value &lt;&lt; std::endl;<br>}<br><br>template &lt;&gt;<br>void printValue&lt;int&gt;(int value) {<br>    // Specialized implementation for integers<br>    std::cout &lt;&lt; &quot;print integer value: &quot; &lt;&lt; value &lt;&lt; std::endl;<br>}<br><br>template &lt;&gt;<br>void printValue&lt;std::string&gt;(std::string value) {<br>    // Specialized implementation for strings<br>    std::cout &lt;&lt; &quot;print string value: &quot; &lt;&lt; value &lt;&lt; std::endl;<br>}<br><br>int main() {<br>    printValue(5);             // Calls specialized version for integers<br>    printValue(3.14);          // Calls the generic version<br>    printValue(&quot;Hello&quot;);       // Calls specialized version for strings<br><br>    return 0;<br>}</pre><p>In this example, we have a generic printValue template function that can handle any data type. However, we provide specialized implementations for int and std::string to perform specific operations or output custom messages. When calling printValue with an int, the specialized version for integers will be invoked, and the same goes for std::string values. For other types, the generic implementation will be used.</p><p>With the introduction of C++11, templates received several enhancements and new features. Let’s explore them:</p><p><a href="https://github.com/AnthonyCalandra/modern-cpp-features#variadic-templates"><strong>Variadic Templates:</strong></a></p><p>The ... syntax creates a parameter pack or expands one. A template parameter pack is a template parameter that accepts zero or more template arguments (non-types, types, or templates). A template with at least one parameter pack is called a variadic template.</p><pre>template &lt;typename... Args&gt;<br>void printAll(Args... args) {<br>    ((std::cout &lt;&lt; args &lt;&lt; &quot; &quot;), ...);<br>}<br><br>printAll(1, 2, 3, &quot;hello&quot;, 3.14);</pre><p><strong>Template Aliases:</strong></p><pre>template &lt;typename T&gt;<br>using Vector = std::vector&lt;T&gt;;<br><br>Vector&lt;int&gt; myVector;</pre><p>Templates in C++ have evolved significantly over the years, providing developers with powerful tools for generic programming. From the foundational features in C++98/03 to the advanced techniques introduced in the latest C++20 standard, templates have continually expanded, offering new features, improved functionality, and enhanced code readability.</p><p>By understanding and leveraging the advancements and new features in each version of C++, developers can unlock the full potential of templates, enabling them to write reusable, flexible, and efficient code. So, let’s embrace the power of templates across different versions of C++ and take our programming skills to new heights.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71d765e976de" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>