<?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 Tushar on Medium]]></title>
        <description><![CDATA[Stories by Tushar on Medium]]></description>
        <link>https://medium.com/@tushargurjar_23597?source=rss-b05ff4d7ae7c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Tushar on Medium</title>
            <link>https://medium.com/@tushargurjar_23597?source=rss-b05ff4d7ae7c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:46:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tushargurjar_23597/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[Writing templatized code (C++)]]></title>
            <link>https://blog.stackademic.com/writing-templatized-code-c-83f1b44e5b7e?source=rss-b05ff4d7ae7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/83f1b44e5b7e</guid>
            <category><![CDATA[sfinae]]></category>
            <category><![CDATA[metaprogramming]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[generic-programming]]></category>
            <dc:creator><![CDATA[Tushar]]></dc:creator>
            <pubDate>Mon, 18 May 2026 08:44:13 GMT</pubDate>
            <atom:updated>2026-05-18T08:44:13.065Z</atom:updated>
            <content:encoded><![CDATA[<p>C++ is, at its core, a language obsessed with two things: <strong>raw speed</strong> and <strong>less code</strong>.</p><p><strong>I. Speed: Feed the Compiler, Reap the Performance</strong></p><p>The compiler is not just a translator; it’s an optimizer waiting to be unleashed. The more you tell it upfront, the more ruthlessly it can act on your behalf.</p><p>This is the whole game behind <em>constexpr</em> and <em>consteval</em>: push computation out of runtime entirely. Behind <em>noexcept</em>, promise the stack won’t unwind, let the compiler breathe easier. Behind <em>[[likely]]</em>, whisper to the branch predictor. Behind non-type template parameters, bake hard facts like matrix dimensions directly into the type, the way Eigen does with <em>Matrix&lt;float, 4, 4&gt;</em>. Behind <em>_restrict_</em>, swear that your pointers don’t alias, unlock a whole class of vectorization. And behind the deliberate spectrum from <em>std::variant</em> (compiler knows exactly what’s in the box), all the way down to <em>std::any</em> (compiler knows nothing, and you pay for that ignorance at runtime).</p><p>One hardcore example from the real world: many HFT traders don’t read config files at startup. They don’t load parameters from a database. They don’t keep types unknown for runtime. Instead, they maintain a <em>types.h</em>, a header that holds the day’s constants, thresholds, risk limits, alpha types, all hardcoded. Every morning, update the header, recompile. A fresh binary, with today’s reality burned directly into it. I like to call it <em>types.h trick</em>.</p><p>The principle is brutal in its simplicity: <strong>every fact you hide from the compiler is a performance tax you pay forever.</strong></p><p><strong>II. Less Code: Write Once, Instantiate Everywhere</strong></p><p>The second obsession is eliminating repetition, not by copy-pasting, but by <em>abstracting over types themselves</em>. Templates let you write an algorithm once and let the compiler stamp out perfectly specialized versions for every type that needs it.</p><p><strong>So, why do you need to write type-templatized code?</strong></p><p>Say you’re building a class that works for a <em>family of types</em> <strong>G</strong>, but certain operations only make sense for subfamily <strong>S₁ ⊂ G</strong>, and others only for <strong>S₂ ⊂ G</strong>. The obvious fix, a separate class per type, quickly falls apart: code duplicates everywhere, and one change means touching every copy.</p><p>The way out is <strong>type templatization</strong>: instead of locking in concrete types upfront, you use abstract placeholders and let the compiler fill them in at instantiation time. Write the logic once; the compiler stamps out concrete versions as needed.</p><p><strong>Can we control what types go in our type-templatized code?</strong></p><p>Unconstrained templates let in the <em>entire universe of C++ types</em>, far too broad. You want to <em>restrict the domain to exactly</em> <strong>G</strong>. And the restriction doesn’t have to stop at type identity, you can go deeper and predicate on <strong>type traits</strong>: characteristics like whether a type is arithmetic, copyable, or satisfies a particular interface.</p><p>Even within <strong>G</strong>, you need <em>selective behaviour</em>: some code should kick in for <strong>S₁</strong>, some for <strong>S₂</strong>, never both. C++ gives you four mechanisms for this:</p><ul><li><strong><em>Template Specialisation</em></strong>: provide an entirely separate implementation for a specific type or subfamily.</li><li><strong><em>SFINAE</em></strong>: goes a step further than specialisation; it can discriminate not just on type identity but on <strong>type traits</strong>. When a substitution is ill-formed, it quietly drops out of overload resolution rather than blowing up with a hard error.</li><li><strong><em>Concepts</em></strong> <em>(C++20)</em>: the modern, readable replacement for SFINAE; same power, far less ceremony.</li><li><strong><em>if constexpr </em></strong>— within a single function body, branch at compile time based on subtype or type traits. The catch: substitution failures here are <strong>hard errors</strong> — there’s no graceful fallback, unlike SFINAE.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tht-y_KsTv96qgWW.png" /></figure><p><strong>How to implement template specialization? How to restrict types in a template?</strong></p><p>We know that templates can be specialized to differentiate code for different types. A generic template and its specialization look like this:</p><pre>template&lt;typename T, typename U&gt;<br>class A{}<br><br>template&lt;typename T&gt;<br>class A&lt;vector&lt;T&gt;, std::string&gt; {}</pre><p>We can add whatever specialization we want, it can be type modifiers, type constructors, or exact type restrictions. Just the universe of types in the specialization needs to be a subset of what we have in the main template. There is one limitation to restriction, which is that specialization restriction is coarse-grained- it’s limited to categories of types, we can’t dig into specific types</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T3qGMCTLNagcWWrE.png" /></figure><p>Functions can’t be specialized like these, because we have overloading for them; we can do the exact same restriction, but we need to be in a function parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*IL7EA0MBBqorW3NY.png" /></figure><p><strong>How to implement SFINAE?</strong></p><p>To prepare SFINAE, we need two ingredients: a type expression and a place where we can put it. A type expression can be built using different ways:</p><ul><li>real type expression</li><li>simulation-based type expression where we use real-variables (<em>decltype + declval</em>),</li><li>validity-based type expression: if a type expression is valid, then generate the given type expression; otherwise, remove this overload. we can use void_t or enable_if for this. Both are the same except void_t will always produce the void type and enable_if will produce give type.</li></ul><p>These types of expressions are usually injected into a class/function signature. They can go in the function parameter or return type. We can also do a fake parameter for a function as well as a class template, where we specify a default value, so the user doesn’t have to pass any extra arguments.</p><p>We can also use SFINAE inside class member functions. In the figure, we have created a type trait <em>is_class </em>using <em>pointer to member. </em>This technique is slightly old-school and goes by a few names, <em>sizeof-overload </em>and<em> sizeof-function</em>-<em>return</em> type traits construction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xbbx9Op-k-oTkvB6.png" /></figure><p><strong>How compiler pick the best overload?</strong></p><p>It’s like conducting an interview process; you first pick up candidates who have the same signature, name, and parameters. Once we have them, we do template substitution. Then remove the candidates that cause SFINAE failures. Finally, pick the most specialized one. Obviously, if multiple specialized, it will cause a compilation error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/0*0g4LUrqF7gwJzr3L.png" /></figure><p><strong>What is <em>typename = void</em>? Why can’t detection idiom work if we did <em>typename=int</em> in primary template and <em>void_t</em> in specialization?</strong></p><p>In templates, we don’t even need to give a default name to a template parameter that we don’t wanna use. So, <em>typename T=void</em> is the same as <em>typename=void</em>. It’s a phantom template parameter. Specialization is only recognized if it matches the primary template’s signature. Write <em>typename = int</em> on one side and <em>typename = void </em>on the other; they become strangers, neither specializing in the other. SFINAE has no home to return to.</p><p><strong>Different types of type-traits? How are type-traits implemented?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k1nDbuqJEEXK2CK0.png" /></figure><p><strong>What is the point of a variadic template?</strong></p><p>Sometimes one type parameter isn’t the abstraction you need. The real question becomes: <em>what if the thing you’re templating over is a list of types itself?</em></p><p>Variadic templates let you express exactly that, not “work for some type G,” but “work for an arbitrary constellation of types G1, G2, … Gn.” The parameter pack is the list; the template is a computation over it.</p><p>The use cases diverge wildly depending on what you <em>do</em> with that list:</p><ul><li><strong>Store</strong> one value of each type → <em>std::tuple</em></li><li><strong>Fold</strong> a boolean predicate across all of them → <em>std::conjunction</em></li><li><strong>Distill</strong> them down to a deduplicated set → type-list filtering</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vhbr2kaaHvzw3Wdi.png" /></figure><p>For std::tuple, if we didn’t have variadic templates, there would be infinite cases to implement.</p><p>partial specialization + recursion technique</p><p><strong>Expanding type traits with variadic templates?</strong></p><p>Some type-traits can be transformative, as we saw. Variadic templates can further expand the universe of type-traits. For instance, <em>std::conjuction</em> can combine multiple type-traits or type-expressions to give a single true/false value.</p><p><strong>What are fold expressions? How are they connected with variadic templates?</strong></p><p>Before fold expression, if we wanted to write a sum function over different types, it was like:</p><pre>template&lt;typename T&gt;<br>T sum(T t){<br>  return t;<br>}<br><br>template&lt;typename T, typename ...Ts&gt;<br>T sum(T t, Ts... ts){<br>  return t+sum(ts...);<br>}</pre><p>This was a lot of boilerplate, writing base case, and all.</p><p>The fold expression introduced in C++17 simplified this problem. Now we can just calculate the sum using a fold expression as follows:</p><pre>template&lt;typename ...Ts&gt;<br>T sum(Ts... ts){<br>  return (... + ts); // left fold<br>}</pre><p><strong>Limitations of fold expression compared to variadic template?</strong></p><p>Fold expression can’t short-circuit. All components are computed, while variadic templates can short-circuit. For instance, std::conjunction short-circuits, but the corresponding fold expression can’t.</p><pre>template&lt;typename T, typename ...Ts&gt;<br>class conjunction{<br>  using type = std::conditional_t&lt;std::is_same&lt;T, false_type&gt;, <br>                                      false_type, <br>                                      conjunction&lt;Ts...&gt;&gt;; // this short circuits<br>}<br><br>template&lt;typename ...Ts&gt;<br>class conjunction{<br>  using type = (... &amp;&amp; Ts);  // this doesn&#39;t short circuit<br>}</pre><p><strong>Variadic template pack expansion rules?</strong></p><p>If we have something like a <em>pattern…</em>, the pattern extends. If we don’t have a pattern, they are just declarations.</p><pre>sizeof…(Ts) -&gt; no pattern, number of types<br>typename… Ts  -&gt; no pattern, template declaration<br>sizeof(Ts),... -&gt; pattern -&gt; sizeof(int), sizeof(float), sizeof(bool)<br>cout &lt;&lt; args &lt;&lt; “ “, ... -&gt; pattern</pre><p><strong>What is sizeof…. fold?</strong></p><p>sizeof… is the simplest “fold”. sizeof…(Ts); gives count of types in pack</p><p><strong>How to create concepts?</strong></p><p>The usual syntax for concepts goes like this:</p><pre>template&lt;typename T&gt;<br>concept MyConcept = <br>requires(T a, T b){<br>  //expression validity check<br>  typename T::value;                           // T should have value <br>  a.function()                                 // valid expression, T should have function()<br>  {a.function()}                               // complex expression<br>  {a.function()} -&gt; std::integral              // return type contrainst<br>  {a.function()} noexcept                      // no except check<br>  <br>  //boolean check<br>  requires sizeof(T) &gt; 8;                      // nested require check boolean true<br>  requires std::is_move_constructible&lt;T&gt;</pre><p><strong>Implement the std::tuple container and the get&lt;i&gt;() function?</strong></p><p>With variadic templates, the technique is to always break the list of types called <strong>template peeling</strong> and do a recursive call.</p><pre>template&lt;typename T&gt;<br>class tuple {<br>  T t;<br>}<br>template&lt;typename T, typename ... Ts&gt;             <br>class tuple: tuple&lt;Ts...&gt; {<br>  T t;<br>}<br>template&lt;size_t I, typename T, typename... Ts&gt;<br>auto get(std::tuple&lt;T, Ts...&gt; t){<br>   if constexpr(I==0)<br>     return t.t;<br>   else <br>     return get&lt;I-1&gt;(static_cast&lt;tuple&lt;Ts...&gt;&amp;&gt;(t))&gt;;   // upcast can be done statically<br>}</pre><p><strong>Implement a zip container in which if the given list of input types is the same, then store them as an array; otherwise, store them as a tuple.</strong></p><pre>//APPROACH 1: specialize for array + SFINEA with void_t<br>template&lt;typename ... Ts, typename = void&gt;             <br>class Zip {<br>  std::tuple&lt;Ts...&gt; t;<br>}<br>template&lt;typename T, typename...Ts&gt;<br>class Zip&lt;T, Ts..., std::void_t&lt; std::conjunction&lt;std::is_same&lt;T, Ts&gt;, ...&gt; &gt; &gt; {<br>  std::array&lt;T, sizeof...(Ts) + 1&gt; t;<br>}<br>//APPROACH 2: specialize + concepts<br>template&lt;typename ... Ts&gt;             <br>class Zip {<br>  std::tuple&lt;Ts...&gt; t;<br>}<br>template&lt;typename T, typename...Ts&gt;<br>class Zip&lt;T, Ts...&gt;<br>requires std::conjunction&lt;std::is_same&lt;T, Ts&gt;, ...&gt;   {    // concept boolean exp <br>  std::array&lt;T, sizeof...(Ts) + 1&gt; t;<br>}</pre><p><strong>Given <em>template&lt;typename… Ts&gt; struct TypeSet</em>, write a class that implements compile-time deduplication — i.e., <em>TypeSet&lt;int, float, int, bool, float&gt;</em> should be equivalent to <em>TypeSet&lt;int, float, bool&gt;</em>. Build a Contains-and-Append utility class.</strong></p><pre>template&lt;typename ...Ts&gt; struct TypeSet{};<br><br>template&lt;typename T&gt; <br>class MakeTypeSet{<br>  using type = TypeSet&lt;T&gt;;<br>}<br>template&lt;typename T, typename ...Ts&gt; <br>class MakeTypeSet{<br>  using type = std::conditional_t&lt;Contains&lt;T,Ts...&gt;,<br>                                MakeTypeSet&lt;Ts...&gt;,<br>                                Append&lt;T, MakeTypeSet&lt;Ts...&gt;&gt;&gt;;<br>}<br>template&lt;typename T, typename T1, typename ...Ts&gt; <br>class Contains{<br>  using type = std::conditional_t&lt;std::is_same&lt;T, T1&gt;, true_type, Contains&lt;T, Ts...&gt;&gt;;<br>}<br>template&lt;typename ...Ts&gt; <br>class Append{<br>  using type = TypeSet&lt;Ts...&gt;;<br>}<br>template&lt;typename T, typename ...Ts&gt;      // specialize on TypeSet<br>class Append&lt;T, TypeSet&lt;Ts...&gt; &gt;{<br>  using type = TypeSet&lt;T, Ts...&gt;;<br>}</pre><p><strong>Note</strong>: <em>std::conditional </em>second and third arguments should be types like <em>true_type</em> and not boolean like true. <em>std::conditional_t is the same as std::conditional::type</em></p><p><em>TypSet&lt;&gt; is an important container that can hold a list of types.</em></p><p><strong>Implement std::apply. What is index_sequence, and how to construct it?</strong></p><p><strong>std::apply </strong>is a utility that takes in a function and a tuple and calls that function with that tuple’s values as arguments. <strong><em>index_sequence</em></strong> is exactly like TypeSet, but for a compile-time integer sequence. It’s mostly used to pass to a function, and the index sequence goes into a function template and can be used for a fold expression just like how variadic templates are used.</p><pre>template&lt;typename F, typename Tuple, size_t ...I&gt;<br>auto apply_impl(F&amp;f, Tuple&amp; t, index_sequence&lt;I...&gt;){ // the function parameter is not useful<br>  return f(std::get&lt;I&gt; &gt; t, ...);<br>}<br><br>template&lt;typename F, typename ...T&gt;<br>auto apply(F&amp; f, std::tuple&lt;T...&gt; t){<br>  auto indseq = make_index_sequence&lt;sizeof...(T)&gt;();<br>  return apply_impl(f, t, indseq);<br>}<br>template&lt;size_t ...I&gt;<br>class index_sequence{}<br>template&lt;size_t N&gt;<br>consteval auto make_index_sequence() {<br>    if constexpr (N == 0)<br>        return index_sequence&lt;&gt;{};<br>    else<br>        return Append&lt;N&gt;(make_index_sequence&lt;N - 1&gt;());<br>    <br>}<br>template&lt;size_t N, size_t ...I&gt;<br>consteval auto Append(index_sequence&lt;I...&gt;){<br>  return index_sequence&lt;I..., N&gt;{};<br>}</pre><p><strong>What is the difference between std::<em>index_sequence</em> and <em>constexpr std::array</em>? Both are fixed?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/0*om3HVueOJMAyZhq7.png" /></figure><p><strong>What is the future of generic programming in C++? What are Reflections (C++26)?</strong></p><p>Reflection is the next leap in generic programming. The idea is simple but powerful: let the compiler expose what it knows about your types, at compile time, so your code can act on it generically.</p><p>With Reflection, you can inspect a class like an X-ray machine scans a bag. You see the structure, every member variable, every function, its name, its type, its signature, its access specifier. All of it, available as a compile-time list that you can iterate over, filter, and act on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XbMEy1r_sauzJ1-6.png" /></figure><p>What you <em>cannot</em> see is what’s inside the function body, the actual logic, the syntax, the instructions. The X-ray shows that there’s a metal object in the bag. It does not tell you what the metal <em>does</em>. Same deal, Reflection sees that a function exists, what it takes, and what it returns. Not how it works inside. The following example illustrates that we don’t need individual print/debug logic for all the classes in code, immensely reducing boilerplate.</p><pre>struct Person {<br>    std::string name;<br>    int age;<br>    void greet() const;<br>};<br>template&lt;typename T&gt;<br>std::string debug(const T&amp; obj)<br>{<br>    std::string out;<br>    out += type_name(^T);<br>    out += &quot;{ &quot;;<br>    bool first = true;<br>    for constexpr (auto member : members_of(^T)){<br>        if (!first)<br>            out += &quot;, &quot;;<br>        first = false;<br>        out += name_of(member);<br>        out += &quot;=&quot;;<br>        out += to_string(value_of(member, obj));<br>    }<br>    out += &quot; }&quot;;<br>    return out;<br>}</pre><blockquote><strong>In Action</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/0*-SYVofiW1CtXWNaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*O2M2orsNjSRX0l6V.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*ib-zdpjMZumEohhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/0*dIe2urDo6QOCznXe.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83f1b44e5b7e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/writing-templatized-code-c-83f1b44e5b7e">Writing templatized code (C++)</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Type-Less Type (C++)]]></title>
            <link>https://blog.stackademic.com/a-type-less-type-c-52103113d58a?source=rss-b05ff4d7ae7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/52103113d58a</guid>
            <category><![CDATA[variant]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[type-erasure]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[cpp26]]></category>
            <dc:creator><![CDATA[Tushar]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 14:00:41 GMT</pubDate>
            <atom:updated>2026-04-29T14:00:41.236Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why do we need a type-less type? And what does it even mean?</strong></p><p>Sometimes you need a single type that can stand in for several, an umbrella that covers multiple shapes. Think of it as a <strong>proxy</strong>, it can be an <em>int</em> today, a <em>string</em> tomorrow, a <em>float</em> next week. Once we have this, you can build arrays of mixed types, pipe them through functions, and treat the whole collection as one uniform thing. This idea goes by a few names. <strong>Union type</strong> is the most common. <strong>Sum type</strong> is the more academic term. And <strong>type erasure</strong> captures the essence well, you’re deliberately blurring type boundaries to gain flexibility.</p><p><strong>Does C++ already have union types?</strong></p><p>Yes, a few flavors. <strong><em>void*</em></strong> is the old-school approach, widely used in the STL. It’s a raw, unconstrained pointer that accepts anything you throw at it. <strong><em>memcpy()</em></strong> is the classic example. Powerful, but zero safety guarantees.</p><p><strong><em>std::any</em></strong> is the modern upgrade, type-safe and capable of storing literally anything. It carries type metadata under the hood and uses it for runtime type checking.</p><p>Now, what if you already know all your types upfront at compile time? That constraint is actually a superpower, it unlocks more efficient approaches. Since the universe of types is fixed, you can assign each one an integer tag, store the value alongside it, and size the storage to fit the largest type in the set.</p><p>Alternatively, we already have a <strong>class hierarchy</strong>, several derived classes sharing a common base, we can lean into that. Store any derived type behind a base class pointer, and let <strong>virtual dispatch</strong> do the heavy lifting, whenever you call a method, it automatically routes to the right derived class at runtime.</p><p>Two very different strategies, both unlocking union-like behavior — one through <strong>tagged storage</strong>, the other through <strong>polymorphism</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/0*cO9YV0PxBuMf5eHR.jpeg" /></figure><p><strong>How to build these union types?</strong></p><p>For types fixed at compile time, <em>std::variant, union, std::expected, std::optional, </em>the compiler knows exactly what it’s dealing with. So storage is allocated <strong>on the stack</strong>: sized to the largest possible type, with a tag alongside it to track which type is currently active. <em>std::variant </em>uses <strong>variadic templates</strong> under the hood to wire this all together elegantly.</p><p>For <strong>virtual polymorphism</strong>, every derived type lives behind a base class pointer. But the compiler has no way of knowing whether it’s pointing at a pure base object or some derived subtype. That information has to live inside the object itself. Since all instances of the same type share the same behavior, this metadata is stored once in static memory as a <strong>vtable</strong>, with each object carrying a <strong>vptr </strong>— a lightweight pointer back to its vtable. Runtime dispatch flows through this chain seamlessly.</p><p>For types <strong>not known at compile time</strong>, think library code, <em>void*, std::any</em> — the <strong>heap</strong> is the natural home, since sizes are unpredictable. But heap allocation carries overhead, so as an optimization, <strong>Small Buffer Optimization (SBO)</strong> kicks in for smaller types: if the value fits, it stays on the stack and skips the heap entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/0*voz97eH8jRzOfLrQ.jpeg" /></figure><p><strong>How these union types ensure regulated access, type safety?</strong></p><p>For types known at compile time, the compiler can bake in type safety instructions, executed at runtime.</p><ul><li><em>std::variant</em>: enforces safety via a runtime switch-case against the stored tag.</li><li><em>union</em>: no guardrails whatsoever. Raw stack storage, full trust placed on the user.</li></ul><p>Virtual polymorphism:</p><ul><li><strong>Upcast</strong> (derived → base): safe by definition, verified at compile time via <em>static_cast&lt;&gt;</em>.</li><li><strong>Downcast</strong> (base → derived): ambiguous to the compiler, so it consults the object’s embedded type info at runtime. <em>dynamic_cast&lt;&gt;</em></li><li><strong>CRTP</strong> (<em>Curiously Recurring Template Parameter</em>): a compile-time trick where the derived class passes <em>itself</em> as a template argument into its own base, letting the base class access derived members without any virtual dispatch. The recursion in the name says it all: <em>class Derived : Base&lt;Derived&gt;</em>.</li></ul><p>For types unknown at compile time — type info must travel with the data.</p><ul><li><em>void*</em>: no safety, no metadata. Completely raw.</li><li><em>std::any</em>: carries <em>type_info</em> internally; <em>any_cast</em> validates it at runtime, making it the type-safe heir to <em>void*</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/0*7ptXu31Obx0tHk28.jpeg" /></figure><p><strong>Can we use reinterpret_cast?</strong></p><p>No, because it just reinterprets same data location through different pointer. No pointer shift, like what happens during <em>dynamic_cast</em> and <em>static_cast</em> above.</p><p><strong>Which union type are fast and which are slow?</strong></p><ul><li>stack ones are fast: <em>variant, union, optional, expected</em></li><li>heap ones are slower: <em>void *, std::any</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/0*AWDuF1VJ_Dd-tFDV.jpeg" /></figure><p><strong>How does union type scale wrt adding new types vs adding new behavior?</strong></p><ul><li>virtual functions (open set): easy to add new types than behavior</li><li>variant (closed set): easy to add new behavior (new visitor) than types.</li></ul><p><strong>Which union type fits which scenario?</strong></p><p>Say you’re pushing multiple request types onto a queue, consumed by another thread. Since all types are known at compile time and each is copyable/movable, <em>std::variant</em> inherits those traits too, making it a natural fit here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/0*EC4fKA_nQ8wQxZSQ.jpeg" /></figure><p>Below demonstrates an example of multi-variant dispatch:</p><pre>struct RequestVisitor {<br>    Connection* conn;<br>    <br>    template&lt;typename RequestT, typename CallbackT&gt;<br>    void operator()(RequestT&amp; req, CallbackT&amp; callback) const {<br>        if constexpr (std::is_same_v&lt;RequestT, HttpRequest&gt; &amp;&amp; std::is_same_v&lt;CallbackT, HttpResponseReceivedHandler&gt;) <br>        {<br>            conn-&gt;httpRequest(req, callback);<br>        } else if constexpr (std::is_same_v&lt;RequestT, HttpsRequest&gt; &amp;&amp; std::is_same_v&lt;CallbackT, HttpsResponseReceivedHandler&gt;) <br>        {<br>            conn-&gt;httpsRequest(req, callback);<br>        } <br>    }<br>};<br>std::visit(RequestVisitor(connection), requestVariant, callbackVariant);</pre><p><strong>Can we trim the boilerplate in the visitor?</strong></p><p>The classic visitor is verbose, <em>if</em>-<em>constexpr</em> everywhere, with the actual logic buried inside. <strong><em>Overload{}</em></strong> cleans this up: it bundles a list of lambdas into a single functor, each lambda becoming an <em>operator()</em> overload. Pass that as your visitor and the right lambda gets dispatched automatically.</p><p>Taking it further, C++26’s<strong> <em>inspect</em></strong> proposal brings pattern matching to the table — match a variant against a type, a value, or a wildcard, all in clean switch-case syntax. No more <em>if constexpr </em>scaffolding, just intent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nXbdoBCS0yzdrYVP.jpeg" /></figure><p><strong>Why <em>decay_t</em>? Why <em>auto&amp;&amp;</em>?</strong></p><p><em>decay_t</em> strips away const and references, giving you a clean, bare type suitable for std::is_same&lt;&gt; comparisons. <em>auto&amp;&amp;, </em>a universal reference, does the opposite: it captures everything perfectly, preserving constness and reference category as-is.</p><pre>const std::variant&lt;Add, Multiply, Print&gt; v = Add{2, 3};<br>std::visit([](auto&amp;&amp; value) {<br>    // ...<br>}, v);</pre><p><strong>What is <em>valueless_by_exception</em>? Why can’t <em>optional</em> go valueless?</strong></p><p>For a normal type, move simply invokes the move constructor. But std::variant can hold different types across assignments and there’s no cross-type move constructor. So variant destructs the old type first, then constructs the new one. If that constructor throws, the variant is left holding nothing, a <em>valueless_by_exception</em> limbo.</p><p>std::optional sidesteps this entirely, it only ever transitions between one type and no type, never between two different types, so a half-constructed state can never arise.</p><p><strong>What’s the issue with duplicate types?</strong></p><p>variant&lt;int, int&gt; is legal, but ambiguous. get&lt;int&gt; doesn’t know which slot you mean. By default, the value lands at the smallest index. To be explicit, use in_place_index.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52103113d58a" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/a-type-less-type-c-52103113d58a">A Type-Less Type (C++)</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>