<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged tuesday-coding-tips</title>
<link>https://coderlegion.com/tag/tuesday-coding-tips</link>
<description>Powered by Question2Answer</description>
<item>
<title>Tuesday Coding Tip 28 — (de)serializing JSON string enum in C#</title>
<link>https://coderlegion.com/29763/tuesday-coding-tip-28-de-serializing-json-string-enum-in-c</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Last time I covered C# JSON serialization, I only showcased the &lt;code&gt;Newtonsoft.Json&lt;/code&gt; library. This time, I will also show the &lt;code&gt;System.Text.Json&lt;/code&gt; way.&lt;/p&gt;
&lt;p&gt;You might want to (de)serialize enums as strings, rather than numeric values. Since C# does not support enums with an underlying type of string, you need to do some extra work. Namely, you have to annotate each value using the &lt;code&gt;EnumMember&lt;/code&gt; annotation and then select the correct converter, once again using annotations.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public enum Mood
{
    [EnumMember(Value = &quot;happy&quot;)]
    Happy,
    [EnumMember(Value = &quot;sad&quot;)]
    Sad,
}

public class Object
{
    [JsonProperty(&quot;mood&quot;)]

    [JsonConverter(typeof(StringEnumConverter))]
    public Mood Mood { get; set; }
}

public static class Program
{
    public static void Main()
    {
        string json = JsonConvert.SerializeObject(new Object
        {
            Mood = Mood.Sad
        });

        Console.WriteLine(json);
        // {&quot;mood&quot;:&quot;sad&quot;}
        Console.WriteLine(JsonConvert.DeserializeObject&amp;lt;Object&amp;gt;(json)!.Mood);
        // Sad
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However, &lt;code&gt;System.Text.Json&lt;/code&gt; doesn’t support &lt;code&gt;EnumMember&lt;/code&gt; annotations out of the box. It takes the literal name of the property instead. You can play with capitalization using options object, but that’s it. Or you can write your own converter. Or you can just use one of the dozen converters from the Internet that do the hard work for you.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System.Runtime.Serialization;
using System.Text.Json.Serialization;

public enum Mood
{
    [EnumMember(Value = &quot;happy&quot;)]
    Happy,
    [EnumMember(Value = &quot;sad&quot;)]
    Sad,
}

public class Object
{
    [JsonPropertyName(&quot;mood&quot;)]
    // To use EnumMember annotations, install Macross.Json.Extensions nuget
    // and use a different converter
    // [JsonConverter(typeof(JsonStringEnumMemberConverter))]
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public Mood Mood { get; set; }
}

public static class Program
{
    public static void Main()
    {
        Object obj = new()
        {
            Mood = Mood.Sad,
        };

        string json = System.Text.Json.JsonSerializer.Serialize(obj);
        Console.WriteLine(json);
        // {&quot;mood&quot;:&quot;Sad&quot;}
        Console.WriteLine(System.Text.Json.JsonSerializer.Deserialize&amp;lt;Object&amp;gt;(json)!.Mood);
        // Sad
    }
}
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/29763/tuesday-coding-tip-28-de-serializing-json-string-enum-in-c</guid>
<pubDate>Tue, 27 Oct 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 27 — Aliasing and ‘using’ in C++</title>
<link>https://coderlegion.com/29762/tuesday-coding-tip-27-aliasing-and-using-in-c</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Every hello world tutorial starts with the command &lt;code&gt;using namespace std;&lt;/code&gt;. This command is dangerous as it allows you to bring all standard symbols into your namespace where they can collide with your own symbols. Depending on the kind of collision, the compiler might not tell you, nor can you be sure which version will be used.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdexcept&amp;gt;

int min(int a, int b)
{
    std::terminate();
}

#include &amp;lt;cmath&amp;gt;

int main() {
    using namespace std; // dangerous
    // better to import specific names like:
    using std::max;

    return min(10, 20); // which min will be called?
    // ::min would disambiguate to the local function
    // std::min would disambiguate to standard
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is better to use the &lt;code&gt;using&lt;/code&gt; keyword to selectively bring symbols into the scope or even alias them to be sure they’re unique (note that namespaces alias differently).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;filesystem&amp;gt;

// Aliasing namespace works differently
namespace fs = std::filesystem;

// from aliasing classes
using Path = fs::path;

bool fileExists(const Path&amp;amp; path)
{
    return fs::exists(path);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The keyword can also be used to expose class template parameters for common usage.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;template&amp;lt;class T&amp;gt;
class Foo {
public:
    // Exposing template type saves time
    // to those who need to get to it
    using DataType = T;

    T getItem() const { return T{}; }
};

int main() {
    Foo&amp;lt;int&amp;gt; foo;
    decltype(foo)::DataType item;
    item = foo.getItem();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And since C++20, you can bring &lt;code&gt;enum&lt;/code&gt; values (selectively or in group) for better ergonomics in enum-based branching.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;enum class EmployeeType {
    JuniorDev,
    MediorDev,
    SeniorDev,
    ScrumMaster,
    ProductManager
};

std::string to_string(EmployeeType et) {
    switch (et)
    {
        using enum EmployeeType; // Since C++20
        case JuniorDev: return &quot;junior&quot;;
        case MediorDev: return &quot;medior&quot;;
        // ...
    }
}

std::string to_string(EmployeeType et) {
    using EmployeeType::JuniorDev;

    if (et == JuniorDev) return &quot;junior&quot;;
    // ...
}
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/29762/tuesday-coding-tip-27-aliasing-and-using-in-c</guid>
<pubDate>Tue, 20 Oct 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 26 — JSON (de)serialization in C#</title>
<link>https://coderlegion.com/29761/tuesday-coding-tip-26-json-de-serialization-in-c</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;In need of a JSON (de)serializer in C#? One option could be to use the built-in &lt;code&gt;System.Text.Json&lt;/code&gt; functionality. Probably the most popular way is to use the &lt;code&gt;Newtonsoft.Json&lt;/code&gt; library which has a richer feature set while maintaining overall simplicity.&lt;/p&gt;
&lt;p&gt;Things are as simple as having a class with a bunch of public attributes and calling serialize on it. Those attributes don’t even have to be trivial types — anything from &lt;code&gt;DateTime&lt;/code&gt; to &lt;code&gt;HashSet&lt;/code&gt; can be easily handled.&lt;/p&gt;
&lt;p&gt;Deserialization is similarly easy — if a key is present, it will be deserialized. If not, the default value for the attribute will be picked instead.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using Newtonsoft.Json;

namespace NetSandbox;

public class ExtendedValues
{
    public long ErrorCode { get; set; }

    public string Message { get; set; } = string.Empty;
};

public class Property
{
    public string Value { get; set; } = &quot;&quot;;
};

public class Protocol
{
    public long Version { get; set; } = -1;

    [JsonProperty(&quot;extended&quot;, NullValueHandling = NullValueHandling.Ignore)]
    public ExtendedValues? ExtendedValues { get; set; } = default;


    [JsonProperty(&quot;machineGuid&quot;)]
    public Guid MachineGuid { get; set; }

    public List&amp;lt;Property&amp;gt; Properties { get; set; } = new List&amp;lt;Property&amp;gt;();
};

public static class Program
{
    public static void Main()
    {
        Protocol schema = new()
        {
            Version = 1,
            MachineGuid = Guid.NewGuid(),
            Properties = new List&amp;lt;Property&amp;gt; {
                new Property {
                    Value = &quot;hello&quot;
                },
                new Property {
                    Value = &quot;world&quot;
                }
            }
        };

        var json = JsonConvert.SerializeObject(schema);
        // {&quot;Version&quot;:1,&quot;machineGuid&quot;:&quot;156717fd-0904-47af-bcb8-ad74d23b9cc7&quot;,&quot;Properties&quot;:[{&quot;Value&quot;:&quot;hello&quot;},{&quot;Value&quot;:&quot;world&quot;}]}

        var obj = JsonConvert.DeserializeObject&amp;lt;Protocol&amp;gt;(
            &quot;&quot;&quot;{&quot;machineGuid&quot;: &quot;156717fd-0904-47af-bcb8-ad74d23b9cc7&quot;}&quot;&quot;&quot;);
        // obj.Version contains -1
        // obj.MachineGuid containts &quot;156717fd-0904-47af-bcb8-ad74d23b9cc7&quot;
        // obj.ExtendedValues is null
        // obj.Properties is empty list
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you need to, you can use annotations to for example customize the name of the serialized property or whether it will be serialized when it is null.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Extra thought:&lt;/strong&gt; I originally wrote this post in late 2023. Since then, many people would probably advice you &lt;code&gt;System.Text.Json&lt;/code&gt; on the merit of being faster and getting more and more on-part with Newtonsoft on each major release. Since we did a switch to it some time ago, I cannot wholeheartedly recommend it - it is great for simple use cases, but once you have some data structure that evolved over time and you need to be lenient of what you accept over wire and strict in what you send, working with &lt;code&gt;System.Text.Json&lt;/code&gt; is a bigger pain, especially around &lt;code&gt;NullValueHandling&lt;/code&gt; and &lt;code&gt;DefaultValueHandling&lt;/code&gt;.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/29761/tuesday-coding-tip-26-json-de-serialization-in-c</guid>
<pubDate>Tue, 13 Oct 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 25 — User-defined literals</title>
<link>https://coderlegion.com/29758/tuesday-coding-tip-25-user-defined-literals</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;C++ has many built-in literals for disambiguating types of constants, such as &lt;code&gt;u&lt;/code&gt; for unsigned, &lt;code&gt;f&lt;/code&gt; for float, or time-related literals from the chrono header (like &lt;code&gt;ms&lt;/code&gt;, &lt;code&gt;h&lt;/code&gt;, or &lt;code&gt;min&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;The really cool thing is that you can define your own literals (since C++11) to make your domain-specific constants more legible. All these literals overload the &lt;code&gt;operator“”&lt;/code&gt; with your custom &lt;code&gt;_suffix&lt;/code&gt;. The data type that is supposed to be before &lt;code&gt;_suffix&lt;/code&gt; is then determined by the function parameter type (consult the documentation for allowed parameter types: &lt;a rel=&quot;nofollow&quot; href=&quot;https://en.cppreference.com/w/cpp/language/user_literal&quot;&gt;https://en.cppreference.com/w/cpp/language/user_literal&lt;/a&gt; ).&lt;/p&gt;
&lt;p&gt;Thanks to compile-time computing, these literals don’t have to imply any runtime overhead for your code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Language-provided literals
const auto foo = 100u; // implies unsigned int
const auto bar = 10.f; // implies float instead of double

// Library-provided literals
#include &amp;lt;chrono&amp;gt;
using namespace std::literals;

const auto baz = &quot;hello&quot;s; // implies std::string instead of const char*
constexpr auto day = 14d; // If the value &amp;gt; 255, then the stored value is unspecified. 
constexpr auto twoDays = 48h;
constexpr auto week = 24h* 7;
constexpr auto my_duration_unit = 108ms;
constexpr auto theYear = 2021y;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;An interesting use-case that I found is that literals can be leveraged to make described bool constants without having to wrap them in a temporary.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Literal that describes a constant in pixel units
[[nodiscard]] consteval unsigned long long operator&quot;&quot;_px(unsigned long long value) {
    return value;
}

const auto SCREEN_WIDTH = 1280_px;

#include &amp;lt;cstddef&amp;gt;

[[nodiscard]] consteval bool operator&quot;&quot;_false(const char*, std::size_t) {
    return false;
}

[[nodiscard]] consteval bool operator&quot;&quot;_true(const char*, std::size_t) {
    return true;
}

foo(&quot;isWindowOpen&quot;_true, &quot;isFullscreen&quot;_false);
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/29758/tuesday-coding-tip-25-user-defined-literals</guid>
<pubDate>Tue, 06 Oct 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 24 — Getting template type from an existing object</title>
<link>https://coderlegion.com/26343/tuesday-coding-tip-24-getting-template-type-from-an-existing-object</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Nice APIs expose their template types as member aliases so that anybody can get them easily. For other types, you might be able to deduce the type by calling &lt;code&gt;decltype&lt;/code&gt; on a return value of some of their functions.&lt;/p&gt;
&lt;p&gt;Sometimes, none of that is possible. But there is still a way to get to it. You need to write a template structure that only matches on the type you care about and alias the template parameters so you can access them later, a technique known as ‘type trait’.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;vector&amp;gt;

// Base template, only for the compiler
template&amp;lt;class T&amp;gt;
struct UnderlyingVectorType {};

// Overload for vector, note that templates don't have to match
template&amp;lt;class T, class A&amp;gt;
struct UnderlyingVectorType&amp;lt;std::vector&amp;lt;T, A&amp;gt;&amp;gt; {
    using StorageType = T;
    using AllocatorType = A;
};

// Nice types already expose their template types
template&amp;lt;class T&amp;gt;
class NiceType {
public:
    using StorageType = T;
};

int main() {
    int a;
    
    // error: no type named 'type' in 'UnderlyingVectorType&amp;lt;int&amp;gt;'
    // because it resolves to the base template
    // UnderlyingVectorType&amp;lt;decltype(a)&amp;gt;::storageType b;

    std::vector&amp;lt;float&amp;gt; vec;
    using VecStorageType = UnderlyingVectorType&amp;lt;decltype(vec)&amp;gt;::StorageType;
    VecStorageType vec2;
    static_assert(std::is_same_v&amp;lt;VecStorageType, float&amp;gt;);

    NiceType&amp;lt;double&amp;gt; nice;
    decltype(nice)::StorageType myDouble = 0.0;
    static_assert(std::is_same_v&amp;lt;decltype(nice)::StorageType, double&amp;gt;);
}
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/26343/tuesday-coding-tip-24-getting-template-type-from-an-existing-object</guid>
<pubDate>Tue, 29 Sep 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 23 — CMake configure_file</title>
<link>https://coderlegion.com/26342/tuesday-coding-tip-23-cmake-configurefile</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;In unit tests, I often don’t want to bother with the working folder of the test binary. But if those tests need physical files from the disc, I need to know their absolute paths (which are different on each machine). Luckily, CMake has a function &lt;code&gt;configure_file&lt;/code&gt; that can write CMake variables to a file template.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cmake&quot;&gt;cmake_minimum_required ( VERSION 3.10 )

set ( USE_MSVC_FEATURES (&quot;${CMAKE_GENERATOR}&quot; MATCHES &quot;Visual Studio 17 2022&quot;) )

project ( DEMO CXX )

# CMakeLists.txt
configure_file(
    &quot;${CMAKE_SOURCE_DIR}/TemplateHeader.hpp.in&quot; # input
    &quot;${CMAKE_SOURCE_DIR}/FinalHeader.hpp&quot; # output
)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For example, I can prepare a template for a header that will hold an absolute path to a folder with helper files, and during configuration, I can produce a valid C++ header with the path filled out. CMake will replace variables escaped as &lt;code&gt;@VAR@&lt;/code&gt;, &lt;code&gt;${VAR}&lt;/code&gt;, &lt;code&gt;$CACHE{VAR}&lt;/code&gt; or &lt;code&gt;$ENV{VAR}&lt;/code&gt; and furthermore it can do things like generating &lt;code&gt;#define&lt;/code&gt; directives.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// TemplateHeader.hpp.in
#pragma once

#include &amp;lt;filesystem&amp;gt;

#cmakedefine01 USE_MSVC_FEATURES

const std::filesystem::path TESTDATA_FOLDER = &quot;@CMAKE_CURRENT_SOURCE_DIR@/TestFiles&quot;;
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// Generated FinalHeader.hpp
#pragma once

#include &amp;lt;filesystem&amp;gt;

#define USE_MSVC_FEATURES 1

const std::filesystem::path TESTDATA_FOLDER = &quot;C:/Work/Project/TestFiles&quot;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Full documentation: &lt;a rel=&quot;nofollow&quot; href=&quot;https://cmake.org/cmake/help/latest/command/configure_file.html&quot;&gt;https://cmake.org/cmake/help/latest/command/configure_file.html&lt;/a&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/26342/tuesday-coding-tip-23-cmake-configurefile</guid>
<pubDate>Tue, 22 Sep 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 22 — Compile-time computing</title>
<link>https://coderlegion.com/26341/tuesday-coding-tip-22-compile-time-computing</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;As you might know, templates in C++ are turing-complete and you can use them for compile-time computing. But they are unwieldy. So the &lt;code&gt;constexpr&lt;/code&gt;/&lt;code&gt;consteval&lt;/code&gt; keywords were created, so you can write a normal code and mark it as viable for compile-time execution. &lt;code&gt;consteval&lt;/code&gt; means that the function has to be executed during compilation (and then optimized away) while &lt;code&gt;constexpr&lt;/code&gt; gives the compiler the opportunity to do so.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;array&amp;gt;

template&amp;lt;unsigned limit&amp;gt;
consteval auto ComputeFibonacciLookup()
{
    std::array&amp;lt;int, limit&amp;gt; result = { 0 };

    unsigned n_1 = 0;
    unsigned n_2 = 1;
    for (unsigned i = 0; i &amp;lt; limit; i++)
    {
        result[i] = (n_1 + n_2);
        n_2 = n_1;
        n_1 = result.at(i);
    }

    return result;
}

constexpr const auto FIB_LOOKUP_TABLE = ComputeFibonacciLookup&amp;lt;10&amp;gt;();
static_assert(FIB_LOOKUP_TABLE.size() == 10u);
static_assert(FIB_LOOKUP_TABLE[0] == 1);
static_assert(FIB_LOOKUP_TABLE[1] == 1);
static_assert(FIB_LOOKUP_TABLE[2] == 2);
static_assert(FIB_LOOKUP_TABLE[3] == 3);
static_assert(FIB_LOOKUP_TABLE[4] == 5);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Why is this useful? For example, you can generate a lookup table to optimize runtime speed while maintaining the table itself via an algorithm, not hard-coded values. Or you can write compile-time unit tests for your code. These are handy the compilation will error out if you have any undefined behavior in your code (that does not happen for regular compilation).&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;constexpr bool divide(int a, int b)
{
    return (a / b) != 0;
}

// Static assert guaratees compile-time execution
static_assert(divide(10, 5)); // ok

// compilation error, division by zero is UB
// error: static assertion expression is not an integral constant expression
static_assert(divide(10, 0));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Extra thought:&lt;/strong&gt; This tip was originally written three years ago. Since then, many more &lt;code&gt;constexpr&lt;/code&gt; variants of standard containers and language constructs were added to the language. Meaning you can do more advanced stuff in the compile time. With C++26, you can even allocate memory and throw exceptions. The compiler will also check that you properly deallocate memory, which is very clever.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Edit 15.9.2026&lt;/strong&gt;: Fixed the first code example as per Mike Dabydeen comment. Kudos for the correction!&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/26341/tuesday-coding-tip-22-compile-time-computing</guid>
<pubDate>Tue, 15 Sep 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 21 — Dangers of Enums</title>
<link>https://coderlegion.com/26340/tuesday-coding-tip-21-dangers-of-enums</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;C++ and C# have a caveat in their &lt;code&gt;enum&lt;/code&gt; types. Each &lt;code&gt;enum&lt;/code&gt; has an underlying storage type which limits a maximum number of values and how much space it takes in memory. However, it also works the other way — it says how many distinct values the &lt;code&gt;enum&lt;/code&gt; handles.&lt;/p&gt;
&lt;p&gt;If you define an &lt;code&gt;enum&lt;/code&gt; with just three values, if it has an underlying type of &lt;code&gt;uint8&lt;/code&gt;, it handles 256 distinct values. You can take any integer up to 255, cast it to that &lt;code&gt;enum&lt;/code&gt; type, and get a “valid” value. When branching on an &lt;code&gt;enum&lt;/code&gt;, you need to keep in mind that you might get an undefined value, especially if it was deserialized from the wire.&lt;/p&gt;
&lt;p&gt;To add insult to injury, compilers won’t warn you by default. Only pattern matching does for C#. C++ can warn you if you don’t cover a defined &lt;code&gt;enum&lt;/code&gt; value in a switch statement, but you must not use the &lt;code&gt;default&lt;/code&gt; case — preventing you from correctly handling ill-formed values.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;iostream&amp;gt;

enum class Mode : char {
    Primary,
    Secondary
};

std::string to_string(Mode mode)
{   
    switch (mode)
    {
        case Mode::Primary: return &quot;Primary&quot;;
        // With -Wswitch-enum
        // warning: enumeration value 'Secondary' not handled in switch
    }
}

std::string to_string2(Mode mode)
{
    switch (mode)
    {
        case Mode::Primary: return &quot;Primary&quot;;
        // With -Wswitch-enum
        // no other warning
        default: return &quot;Undefined&quot;;
    }
}

std::string to_string3(Mode mode)
{
    switch (mode)
    {
        case Mode::Primary: return &quot;Primary&quot;;
        case Mode::Secondary: return &quot;Secondary&quot;;
        // With -Wswitch-enum
        // no other warning
    }
}

int main()
{
    auto&amp;amp;&amp;amp; str = to_string3(static_cast&amp;lt;Mode&amp;gt;(42));
    std::cout &amp;lt;&amp;lt; str &amp;lt;&amp;lt; std::endl; // Output is an undefined behaviour
    return 0;
}
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/26340/tuesday-coding-tip-21-dangers-of-enums</guid>
<pubDate>Tue, 08 Sep 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 20 — Be `explicit`!</title>
<link>https://coderlegion.com/21475/tuesday-coding-tip-20-be-explicit</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;If you choose to add a conversion operator for your class in C++, be sure to mark it as &lt;code&gt;explicit&lt;/code&gt; or you can get nasty side-effects that will be hard to debug. For example, having an implicit conversion operator to bool will make the operator less-than “work” for your class, meaning that class can be used as a key for &lt;code&gt;std::map&lt;/code&gt; and suddenly, all hell breaks loose.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;

class A {
public:
    operator bool() {
        return true;
    }
};

class B {
public:
    explicit operator bool() {
        return true;
    }
};

int main() {
    // This is ok
    std::cout &amp;lt;&amp;lt; (A() &amp;lt; A()) &amp;lt;&amp;lt; std::endl;
    A a;
    if (a); // implicit conversion allowed

    // Error: error: invalid operands to binary expression
    std::cout &amp;lt;&amp;lt; (B() &amp;lt; B()) &amp;lt;&amp;lt; std::endl;
    B b;
    if (bool(b)); // explicit conversion required

    return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Similarly, it is good practice to mark single parameter constructors &lt;code&gt;explicit&lt;/code&gt; to prevent implicit conversions from trivial data types or to possibly track places where your object is copied.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class A {
public:
    A(int) {}
    A(const A&amp;amp;) {}
};

class B {
public:
    explicit B(int) {}
    explicit B(const B&amp;amp;) {}
};

int main() {
    A a1 = 10; // ok
    A a2 = { 10 }; // ok
    A a3 = a1; // ok

    B b1 = 10; // error: no viable conversion, explicit constructor is not a candidate
    B b2 = { 10 }; // error
    B b3 = B{10}; // ok
    B b4 = b1; // error
    B b5 = B{b1}; // ok

    return 0;
}
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/21475/tuesday-coding-tip-20-be-explicit</guid>
<pubDate>Tue, 21 Jul 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 19 — [[nodiscard]] annotation</title>
<link>https://coderlegion.com/21474/tuesday-coding-tip-19-nodiscard-annotation</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Since C++17, one can use &lt;code&gt;[[nodiscard]]&lt;/code&gt; annotation to mark API functions whose return values should not be discarded without consideration. This usually applies to methods that make no sense to call without evaluating their return value (like predicate functions such as &lt;code&gt;empty&lt;/code&gt; or a factory function). The compiler will issue a warning if the return value is not handled.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class [[nodiscard]] A {};

// OR

class B {
public:
    [[nodiscard]] B() = default;
};

// Enums can be nodiscard too
enum class [[nodiscard]] State {
    Default,
    Foo,
    Bar
};

int main()
{
    // warning: ignoring temporary created by a constructor declared with 'nodiscard' attribute
    A();
    B();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But beware! Sometimes it might be tempting to return some scope guard that will maintain postconditions automatically at the end of the scope using RAII (such as committing transactions). However, a user of your API can pipe the result of your &lt;code&gt;nodiscard&lt;/code&gt; function into a &lt;code&gt;std::ignore&lt;/code&gt; helper which causes the temporary to destruct immediately, defeating the idea of end-of-scope cleanup.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;tuple&amp;gt; // std::ignore

class [[nodiscard]] A {};
class B {
public:
    [[nodiscard]] bool isOk() const { return true; }
};

// no need for nodiscard, A is nodiscard
A foo() {
    return A();
}

// B is not nodiscard, mark it explicitly
[[nodiscard]] B bar() {
    return B();
}

int main()
{    
    foo(); // warning: ignoring temporary created by a constructor declared with 'nodiscard' attribute
    bar(); // warning

    std::ignore = foo(); // ok
    auto b = bar(); // ok
    b.isOk(); // warning
    if (b.isOk()) {} // ok
}
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/21474/tuesday-coding-tip-19-nodiscard-annotation</guid>
<pubDate>Tue, 14 Jul 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 18 — Generating random numbers in C++</title>
<link>https://coderlegion.com/21473/tuesday-coding-tip-18-generating-random-numbers-in-c</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Classic C way of generating random numbers is to set the current time as a seed and then modulo results of the rand function to get somewhat random numbers (modulo can introduce bias based on the implementation of rand).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;random&amp;gt;

// Get random integer in range &amp;lt;min, max)
int getRandomNumber(int min, int max)
{
    return rand() % (max - min) + min;
}

int main()
{
    // seeding with current time to get different output each time
    srand(time(NULL));

    for (int i = 0; i &amp;lt; 10; i++)
        std::cout &amp;lt;&amp;lt; getRandomNumber(10, 20) &amp;lt;&amp;lt; std::endl;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;C++11 introduces the concept of engines, adaptors, and distributions. Engines are seedable and give you random numbers similar to &lt;code&gt;rand()&lt;/code&gt; calls. However, each engine is implemented differently, impacting its speed and memory footprint. Adapters tamper with RNG output, such as shuffling the order of output values or discarding them.&lt;/p&gt;
&lt;p&gt;Distributions transform the output from the generators to get values in certain ranges and probabilistic properties, such as the middle value being the most probable (normal distribution). Distributions are more nuanced than just using the modulo operator so their outputs are more suitable for cryptography use-cases.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;random&amp;gt;

// Get random integer in range &amp;lt;min, max)
int getRandomNumber(int min, int max)
{
    return rand() % (max - min) + min;
}

int main()
{
    std::random_device rd; // non-seedable source of non-deterministic numbers from hardware
    std::mt19937 generator(rd()); // deterministic generator with uniform distribution
                                  // seeded with totally random number

    std::uniform_int_distribution&amp;lt;&amp;gt; distribution(10, 19);

    for (int i = 0; i &amp;lt; 10; i++)
        std::cout &amp;lt;&amp;lt; distribution(generator) &amp;lt;&amp;lt; std::endl;
}
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/21473/tuesday-coding-tip-18-generating-random-numbers-in-c</guid>
<pubDate>Tue, 07 Jul 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 17 — Wrapping C APIs</title>
<link>https://coderlegion.com/21472/tuesday-coding-tip-17-wrapping-c-apis</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Resource Acquisition is Initialization (RAII) is an awfully named principle saying that your class should be fully usable after construction and should clean itself up in the destructor (in other words, no (de)init methods). This principle is common in modern programming languages and is also adopted in modern C++ codebases.&lt;/p&gt;
&lt;p&gt;But what if you work with C-like API like &lt;code&gt;fopen&lt;/code&gt;? It returns a pointer you need to manually free before it goes out of scope. Otherwise, you leak memory and open file handles. This is where smart pointers come to the rescue as you can wrap raw pointers with them and give them custom callbacks to execute when they leave the scope.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;cstdlib&amp;gt;
#include &amp;lt;iostream&amp;gt;
#include &amp;lt;memory&amp;gt;

// MSVC disallows calling fopen
#pragma warning(disable : 4996)

void CloseFile(FILE* f)
{
    std::cout &amp;lt;&amp;lt; &quot;Closing file&quot; &amp;lt;&amp;lt; std::endl;
    fclose(f);
}

auto SafeFopen(const char* path, const char* mode)
{
    return std::unique_ptr&amp;lt;FILE, decltype(&amp;amp;CloseFile)&amp;gt;(
        fopen(path, mode), CloseFile);
}

int main()
{
    auto&amp;amp;&amp;amp; fp = SafeFopen(&quot;myfile.txt&quot;, &quot;w&quot;);
    return 0;
    // Outputs: Closing file
}
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/21472/tuesday-coding-tip-17-wrapping-c-apis</guid>
<pubDate>Tue, 30 Jun 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 16 — Creating objects in existing memory</title>
<link>https://coderlegion.com/19946/tuesday-coding-tip-16-creating-objects-in-existing-memory</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;C++ allows you to scrap your OS’ memory allocators, get yourself a huge chunk of memory and write your own allocators (they can be used with the standard library). It’s a hardcore optimization, but here’s a related tip that might be handy in normal projects as well.&lt;/p&gt;
&lt;p&gt;When using the operator &lt;code&gt;new&lt;/code&gt;, one can provide it with an already allocated memory, so it runs a constructor for a particular type in there. After that, reinterpret that memory as a pointer to your desired object and use it normally. However, deletion is a bit more complicated, as you have to call the destructor on that object manually (because &lt;code&gt;delete&lt;/code&gt; must be called on the original memory, not the object).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// using some template type T
auto&amp;amp;&amp;amp; buffer = static_cast&amp;lt;std::byte*&amp;gt;(::operator new(sizeof(T)));
if (!buffer) throw std::bad_alloc();

new (buffer) T();
auto&amp;amp;&amp;amp; object = reinterpret_cast&amp;lt;T*&amp;gt;(buffer);

// ...

object-&amp;gt;~T(); // call destructor
delete[] buffer; // properly release memory
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I used this trick when implementing a resource manager that needs to hold any user data type (that is still default-constructible in my case): &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/nerudaj/dgm-lib/blob/main/lib/include/DGM/classes/ResourceManager.hpp&quot;&gt;link&lt;/a&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/19946/tuesday-coding-tip-16-creating-objects-in-existing-memory</guid>
<pubDate>Tue, 16 Jun 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 15 — Mathematical constants in C++</title>
<link>https://coderlegion.com/19942/tuesday-coding-tip-15-mathematical-constants-in-c</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and LinkedIn.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Since C++20, you can include header &lt;code&gt;&amp;lt;numbers&amp;gt;&lt;/code&gt; and use many commonly used, precomputed mathematical constants like Pi, Phi, square root of 2 and 3, natural logarithms of 2 and 10, and many more! Even better, you can choose their precision by specifying the underlying type via a template.&lt;/p&gt;
&lt;p&gt;And since C++17, the &lt;code&gt;&amp;lt;cmath&amp;gt;&lt;/code&gt; header contains some special math functions I’ve never heard of like cylindrical Bessel functions, associated Legendre polynomials, or Riemann zeta function.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;numbers&amp;gt;
#include &amp;lt;iomanip&amp;gt; // std::setprecision
#include &amp;lt;limits&amp;gt; // std::numeric_limits

template&amp;lt;typename T&amp;gt;
void printConstant(T value)
{
    const auto default_precision{std::cout.precision()};

    std::cout &amp;lt;&amp;lt; std::setprecision(std::numeric_limits&amp;lt;T&amp;gt;::digits10 + 1);
    std::cout &amp;lt;&amp;lt; value &amp;lt;&amp;lt; std::endl;

    std::cout &amp;lt;&amp;lt; std::setprecision(default_precision);
}

int main()
{
    using namespace std::numbers;
    printConstant(pi_v&amp;lt;float&amp;gt;);
    printConstant(pi_v&amp;lt;double&amp;gt;);
    printConstant(pi_v&amp;lt;long double&amp;gt;);

    /* Outputs:
    3.141593
    3.141592653589793
    3.141592653589793239
    */
}
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;Constants are documented here: &lt;a rel=&quot;nofollow&quot; href=&quot;https://en.cppreference.com/w/cpp/numeric/constants&quot;&gt;https://en.cppreference.com/w/cpp/numeric/constants&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Special functions are documented here: &lt;a rel=&quot;nofollow&quot; href=&quot;https://en.cppreference.com/w/cpp/numeric/special_functions&quot;&gt;https://en.cppreference.com/w/cpp/numeric/special_functions&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/19942/tuesday-coding-tip-15-mathematical-constants-in-c</guid>
<pubDate>Tue, 09 Jun 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 14 — Pattern matching in C#</title>
<link>https://coderlegion.com/18837/tuesday-coding-tip-14-pattern-matching-in-c</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Since C# 7, you can use pattern matching to write simple and safer code. First, it allows you to return a value from a switch expression, saving you the hassle of creating a temporary on a separate line.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public enum State {
    None, Foo, Bar
}

public void PrintState(State state)
{
    // Original switch
    switch (state)
    {
        case State.Foo:
            Console.WriteLine(&quot;Foo&quot;); break;
        case State.Bar:
            Console.WriteLine(&quot;Bar&quot;); break;
        default:
            Console.WriteLine(&quot;None&quot;); break;
    }

    // Rewritten switch
    Console.WriteLine(state switch {
        State.Foo =&amp;gt; &quot;Foo&quot;,
        State.Bar =&amp;gt; &quot;Bar&quot;,
        _ =&amp;gt; &quot;None&quot;
    });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Second, it can match not only on discrete values but expressions as well and the compiler can warn you if some expression is redundant (relational patterns).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static string SubjectiveTemp(int degrees)
{
    // Relation patterns were added in C# 9
    return degrees switch
    {
        -273 =&amp;gt; &quot;Absolute zero&quot;,
        &amp;gt;-273 and &amp;lt;-10 =&amp;gt; &quot;Freezing cold&quot;,
        &amp;gt;-10 and &amp;lt;10 =&amp;gt; &quot;Cold&quot;,
        &amp;gt;10 and &amp;lt;25 =&amp;gt; &quot;Livable&quot;,
        _ =&amp;gt; &quot;HOT!&quot;
    };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Third, it can match on more than one value through records, lists, etc. As a cherry on top, pattern matching also encapsulates type and null matching.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static void CustomPrint&amp;lt;T&amp;gt;(T? value)
{
    if (value is int)
        Console.WriteLine($&quot;int: {value}&quot;);
    else if (value is string)
        Console.WriteLine($&quot;string: {value}&quot;);
    else if (value is null)
        Console.WriteLine($&quot;null&quot;);
    else
        Console.WriteLine(&quot;unknown&quot;);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that when pattern matching, the &lt;code&gt;_&lt;/code&gt; symbol is the discard pattern, matching everything that reaches it. Also, switches do not by default warn the user if they forget a branch (usually with enums). Pattern matching does detect and warns on such occasions.&lt;/p&gt;
&lt;p&gt;More on pattern matching: &lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching&quot;&gt;https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching&lt;/a&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/18837/tuesday-coding-tip-14-pattern-matching-in-c</guid>
<pubDate>Tue, 02 Jun 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 13 — Deleting problematic overloads</title>
<link>https://coderlegion.com/18836/tuesday-coding-tip-13-deleting-problematic-overloads</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Suppose you have a C++ function for opening a file stream that accepts a path to a file and a string (view) with open-mode specifications (like &lt;code&gt;fopen&lt;/code&gt;). The issue is, even though your API is strongly typed, users can still swap the arguments by accident and don’t get a compile time error, due to implicit conversions from string-like constants.&lt;/p&gt;
&lt;p&gt;Luckily, there is an easy hack with which you can disable implicit conversions for one particular function by explicitly deleting all overloads (via &lt;code&gt;auto&lt;/code&gt; template) and allowing just one particular version. The coolest thing is that even the return value doesn’t have to match!&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;filesystem&amp;gt;

using path = std::filesystem::path;

void fopen2(const auto&amp;amp;, const auto&amp;amp;) = delete;

FILE* fopen2(const path&amp;amp; fp, const std::string&amp;amp; mode)
{
    /* dummy implementation */
    return nullptr;
}

int main()
{
    // error: call to deleted function 'fopen2'
    // note: candidate function [with auto:1 = char[11], auto:2 = char[2]] has been explicitly deleted
    fopen2(&quot;myfile.txt&quot;, &quot;r&quot;);

    // This is ok
    fopen2(path { &quot;myfile.txt&quot; }, std::string { &quot;r&quot; });
    return 0;
}
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/18836/tuesday-coding-tip-13-deleting-problematic-overloads</guid>
<pubDate>Tue, 26 May 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 12 — Stack trace</title>
<link>https://coderlegion.com/17200/tuesday-coding-tip-12-stack-trace</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;C++23 brings a new feature that I always wanted since I’ve seen it in C# — stack trace.&lt;/p&gt;
&lt;p&gt;When combined with exceptions, it can immensely help with the analysis of user error reports, when you cannot simply attach a debugger. The code snippet shows how to create an exception class that can automatically capture stack trace at the point where it was constructed.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;stacktrace&amp;gt;
#include &amp;lt;stdexcept&amp;gt;

class stacktrace_error : public std::runtime_error
{
public:
    stacktrace_error(std::stacktrace trace = std::stacktrace::current())
        : std::runtime_error(std::to_string(trace))
    {}
};

void bar() { throw stacktrace_error(); }
void foo() { bar(); }

int main()
{
    try
    {
        foo();
    }
    catch (std::exception&amp;amp; e)
    {
        std::cerr &amp;lt;&amp;lt; e.what() &amp;lt;&amp;lt; std::endl;
        /* OUTPUTS:
        0&amp;gt; C:\...\Main.cpp(19): Sandbox!bar+0x44
        1&amp;gt; C:\...\Main.cpp(25): Sandbox!foo+0x20
        2&amp;gt; C:\...\Main.cpp(31): Sandbox!main+0x32
        3&amp;gt; D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl(79): Sandbox!invoke_main+0x39
        4&amp;gt; D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl(288): Sandbox!__scrt_common_main_seh+0x12E
        5&amp;gt; D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl(331): Sandbox!__scrt_common_main+0xE
        6&amp;gt; D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_main.cpp(17): Sandbox!mainCRTStartup+0xE
        7&amp;gt; KERNEL32!BaseThreadInitThunk+0x14
        8&amp;gt; ntdll!RtlUserThreadStart+0x21
        */
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The API even allows you to iterate over each stack entry, but honestly — who needs that?&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: Linux versions of GCC and Clang have this stupid idea of requiring you to manually link stacktrace (akin to math library), because &lt;code&gt;-std=c++23&lt;/code&gt; is apparently not enough of a feature flag. So don't forget to use &lt;code&gt;-lstdc++_libbacktrace&lt;/code&gt; argument for compilation.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/17200/tuesday-coding-tip-12-stack-trace</guid>
<pubDate>Tue, 19 May 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 11 — null-coalescing operator</title>
<link>https://coderlegion.com/17199/tuesday-coding-tip-11-null-coalescing-operator</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Some languages, like C# or Javascript, have a special operator ?? which is a specialization over the normal ternary operator. It either returns the value of the left operand or, if it is null, it returns the value of the right operand.&lt;/p&gt;
&lt;p&gt;Furthermore, the ??= operator allows you to only assign to a variable if it is null. Syntax among languages might differ, so check out this overview: &lt;a rel=&quot;nofollow&quot; href=&quot;https://en.wikipedia.org/wiki/Null_coalescing_operator&quot;&gt;https://en.wikipedia.org/wiki/Null_coalescing_operator&lt;/a&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var a = null;

// Initialize b with a, or with 42 if a is null
var b;
if (a == null) b = 42;
else b = a;

// Shorter version with ?? operator
var c = a ?? 42;

// Update a with something if it is null
a ??= 24;
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/17199/tuesday-coding-tip-11-null-coalescing-operator</guid>
<pubDate>Tue, 12 May 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>What’s Your Worst Production Incident So Far? (And What It Teaches You as a Developer)</title>
<link>https://coderlegion.com/16789/whats-your-worst-production-incident-so-far-and-what-it-teaches-you-as-a-developer</link>
<description>&lt;h3 id=&quot;the-problem-it-worked-locally-until-production-broke-everything-&quot;&gt;The Problem → “It Worked Locally… Until Production Broke Everything”&lt;/h3&gt;
&lt;p&gt;Every developer has that moment.&lt;/p&gt;
&lt;p&gt;You deploy with confidence.&lt;br&gt;
Tests pass. Code looks clean. Everything seems fine.&lt;/p&gt;
&lt;p&gt;Then production happens.&lt;/p&gt;
&lt;p&gt;Suddenly:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Users can’t log in&lt;/li&gt;
&lt;li&gt;Payments fail&lt;/li&gt;
&lt;li&gt;APIs start timing out&lt;/li&gt;
&lt;li&gt;Your phone won’t stop buzzing&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;And you’re sitting there thinking:&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;em&gt;“How did this even happen?”&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;If you’ve never experienced a production incident, you’re either new… or it’s coming.&lt;/p&gt;
&lt;h3 id=&quot;the-solution-learn-from-incidents-don-t-just-survive-them&quot;&gt;The Solution → Learn From Incidents, Don’t Just Survive Them&lt;/h3&gt;
&lt;p&gt;Production incidents are painful.&lt;/p&gt;
&lt;p&gt;But they’re also one of the fastest ways to grow as a developer.&lt;/p&gt;
&lt;p&gt;Not because they break your system&lt;br&gt;
But because they expose how you think, design, and prepare.&lt;/p&gt;
&lt;h3 id=&quot;my-worst-production-incident-and-why-i-ll-never-forget-it-&quot;&gt;My Worst Production Incident (And Why I’ll Never Forget It)&lt;/h3&gt;
&lt;p&gt;Let me be real.&lt;/p&gt;
&lt;p&gt;One of my worst incidents came from something that looked &lt;em&gt;harmless&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;A simple update.&lt;/p&gt;
&lt;p&gt;Nothing complex.&lt;/p&gt;
&lt;p&gt;Just a small change to improve performance.&lt;/p&gt;
&lt;h4 id=&quot;what-happened&quot;&gt;What Happened&lt;/h4&gt;
&lt;p&gt;We deployed a backend update (Laravel API).&lt;/p&gt;
&lt;p&gt;Shortly after:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Requests started slowing down&lt;/li&gt;
&lt;li&gt;Some endpoints began failing&lt;/li&gt;
&lt;li&gt;Database CPU usage spiked&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;At first glance, nothing obvious stood out.&lt;/p&gt;
&lt;p&gt;Monitoring showed increased load but no clear root cause.&lt;/p&gt;
&lt;hr&gt;
&lt;div class=&quot;div-red&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;The most dangerous production issues are the ones that don’t fail immediately they degrade your system gradually.&lt;/span&gt;
&lt;/div&gt;
&lt;h4 id=&quot;the-root-cause&quot;&gt;The Root Cause&lt;/h4&gt;
&lt;p&gt;After digging deeper, we found it:&lt;/p&gt;
&lt;p&gt;A query that worked fine in development&lt;br&gt;
But under production traffic?&lt;/p&gt;
&lt;p&gt;It became a bottleneck.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Missing index&lt;/li&gt;
&lt;li&gt;Repeated calls&lt;/li&gt;
&lt;li&gt;No caching&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;One small oversight… multiplied by thousands of requests.&lt;/p&gt;
&lt;h3 id=&quot;what-made-it-worse&quot;&gt;What Made It Worse&lt;/h3&gt;
&lt;p&gt;It wasn’t just the bug.&lt;/p&gt;
&lt;p&gt;It was everything around it:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;No proper caching strategy&lt;/li&gt;
&lt;li&gt;Limited visibility into queries&lt;/li&gt;
&lt;li&gt;Logs weren’t detailed enough&lt;/li&gt;
&lt;li&gt;No tracing to follow requests&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So debugging took longer than it should have.&lt;/p&gt;
&lt;hr&gt;
&lt;div class=&quot;div-blue&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Production issues are rarely caused by one mistake they are usually a combination of small gaps.&lt;/span&gt;
&lt;/div&gt;
&lt;h3 id=&quot;the-real-lessons-that-changed-how-i-build-systems&quot;&gt;The Real Lessons That Changed How I Build Systems&lt;/h3&gt;
&lt;p&gt;That incident forced a shift in how I approach development.&lt;/p&gt;
&lt;h4 id=&quot;1-works-locally-means-nothing-at-scale&quot;&gt;1. “Works Locally” Means Nothing at Scale&lt;/h4&gt;
&lt;p&gt;Local environments lie.&lt;/p&gt;
&lt;p&gt;They don’t simulate:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Real traffic&lt;/li&gt;
&lt;li&gt;Concurrency&lt;/li&gt;
&lt;li&gt;Data volume&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Now, I always ask:&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;em&gt;“What happens when this runs 1,000 times per minute?”&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4 id=&quot;2-observability-is-not-optional&quot;&gt;2. Observability Is Not Optional&lt;/h4&gt;
&lt;p&gt;After that incident, I stopped treating logging and monitoring as “extras.”&lt;/p&gt;
&lt;p&gt;Now I ensure:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Structured logs&lt;/li&gt;
&lt;li&gt;Query tracking&lt;/li&gt;
&lt;li&gt;Request tracing&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Because when something breaks, you need answers fast.&lt;/p&gt;
&lt;h4 id=&quot;3-caching-is-not-just-an-optimization&quot;&gt;3. Caching Is Not Just an Optimization&lt;/h4&gt;
&lt;p&gt;Before, caching felt like a “nice to have.”&lt;/p&gt;
&lt;p&gt;Now?&lt;/p&gt;
&lt;p&gt;It’s part of system design.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Reduce repeated queries&lt;/li&gt;
&lt;li&gt;Improve performance&lt;/li&gt;
&lt;li&gt;Protect your database&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;If your system depends on repeated data access, caching should be part of your first design not an afterthought.&lt;/span&gt;
&lt;/div&gt;
&lt;h4 id=&quot;4-small-changes-can-have-big-impact&quot;&gt;4. Small Changes Can Have Big Impact&lt;/h4&gt;
&lt;p&gt;The change that caused the issue?&lt;/p&gt;
&lt;p&gt;It looked insignificant.&lt;/p&gt;
&lt;p&gt;But in production, scale amplifies everything.&lt;/p&gt;
&lt;p&gt;Now I treat every change like it can break something.&lt;/p&gt;
&lt;p&gt;Because it can.&lt;/p&gt;
&lt;h4 id=&quot;5-incidents-are-feedback-not-failure&quot;&gt;5. Incidents Are Feedback, Not Failure&lt;/h4&gt;
&lt;p&gt;At the time, it felt like failure.&lt;/p&gt;
&lt;p&gt;Now I see it differently.&lt;/p&gt;
&lt;p&gt;That incident improved:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;My debugging skills&lt;/li&gt;
&lt;li&gt;My system design thinking&lt;/li&gt;
&lt;li&gt;My awareness of edge cases&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;how-i-handle-production-risks-now&quot;&gt;How I Handle Production Risks Now&lt;/h3&gt;
&lt;p&gt;Here’s what I do differently today:&lt;/p&gt;
&lt;h4 id=&quot;before-deployment-&quot;&gt;Before Deployment:&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Review code with edge cases in mind&lt;/li&gt;
&lt;li&gt;Test with realistic data&lt;/li&gt;
&lt;li&gt;Think about performance impact&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;during-development-&quot;&gt;During Development:&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Add logs intentionally&lt;/li&gt;
&lt;li&gt;Structure responses clearly&lt;/li&gt;
&lt;li&gt;Avoid unnecessary queries&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;after-deployment-&quot;&gt;After Deployment:&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;Monitor closely&lt;/li&gt;
&lt;li&gt;Watch metrics and logs&lt;/li&gt;
&lt;li&gt;Be ready to respond fast&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;the-question-every-developer-should-ask&quot;&gt;The Question Every Developer Should Ask&lt;/h3&gt;
&lt;p&gt;Instead of avoiding incidents, ask:&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;em&gt;“Am I prepared when it happens?”&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Because it will.&lt;/p&gt;
&lt;p&gt;And when it does, your preparation matters more than your code.&lt;/p&gt;
&lt;hr&gt;
&lt;div class=&quot;div-faq&quot;&gt;
&lt;span class=&quot;faq-header&quot;&gt;FAQ&lt;/span&gt;
&lt;span class=&quot;faq-body&quot;&gt;
&lt;strong&gt;What causes most production incidents?&lt;/strong&gt;&lt;br&gt;
Common causes include untested edge cases, performance issues, missing caching, and poor observability.&lt;br&gt;&lt;br&gt;

&lt;strong&gt;How can developers reduce production failures?&lt;/strong&gt;&lt;br&gt;
By improving testing, adding proper logging, using caching, and monitoring system behavior in real time.&lt;br&gt;&lt;br&gt;

&lt;strong&gt;Is it normal to have production incidents?&lt;/strong&gt;&lt;br&gt;
Yes. Every developer and team experiences them. What matters is how you learn and improve from them. &lt;/span&gt;

&lt;/div&gt;
&lt;hr&gt;
&lt;h3 id=&quot;final-thoughts&quot;&gt;Final Thoughts&lt;/h3&gt;
&lt;p&gt;Every developer has a “worst production incident.”&lt;/p&gt;
&lt;p&gt;It’s not a matter of &lt;em&gt;if&lt;/em&gt; it’s &lt;em&gt;when&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;But here’s the difference:&lt;/p&gt;
&lt;p&gt;Some developers panic…&lt;br&gt;
Others learn, adapt, and become better.&lt;/p&gt;
&lt;p&gt;The real goal is not to avoid mistakes completely.&lt;/p&gt;
&lt;p&gt;It’s to:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Detect them faster&lt;/li&gt;
&lt;li&gt;Understand them better&lt;/li&gt;
&lt;li&gt;Fix them smarter&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;call-to-action&quot;&gt;Call to Action&lt;/h3&gt;
&lt;p&gt;Now I’ll ask you:&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;em&gt;What’s your worst production incident so far?&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;ul&gt;
&lt;li&gt;Share it with your team&lt;/li&gt;
&lt;li&gt;Talk about it&lt;/li&gt;
&lt;li&gt;Learn from it&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Because sometimes: The best lessons don’t come from success they come from things breaking at the worst possible time.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/16789/whats-your-worst-production-incident-so-far-and-what-it-teaches-you-as-a-developer</guid>
<pubDate>Tue, 05 May 2026 22:23:59 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 10— CTest</title>
<link>https://coderlegion.com/15918/tuesday-coding-tip-10-ctest</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;CMake can do many things and instrumenting your test suite is one of them. Use &lt;code&gt;add_test&lt;/code&gt; to tell cmake it should run a particular command with given parameters. If it returns zero, it succeeded. You can use it to simply run a testrunner binary or to make a matrix of input parameters that are expected to not crash the program.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;cmake_minimum_required ( VERSION 3.26 )

project ( testrunner )
add_executable ( ${PROJECT_NAME} Main.cpp )

enable_testing()
add_test(
   NAME &quot;Example with no params&quot;
   COMMAND ${PROJECT_NAME}
)

add_test(
   NAME &quot;Example with help param&quot;
   COMMAND ${PROJECT_NAME} -h
)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In order to &lt;code&gt;add_test&lt;/code&gt; do anything, one has to also call &lt;code&gt;enable_testing()&lt;/code&gt;. Running the tests is just a matter of running ctest from command line. Just note that ctest requires you to specify a build configuration if you have more than one.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=4332370757284522768&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/15918/tuesday-coding-tip-10-ctest</guid>
<pubDate>Tue, 05 May 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 09 — Source location</title>
<link>https://coderlegion.com/15917/tuesday-coding-tip-09-source-location</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;If you want to log a filename and line number prior to C++20, you need to use the likes of &lt;code&gt;__FILE__&lt;/code&gt; and &lt;code&gt;__LINE__&lt;/code&gt; macros. To use those easily, you have to create a wrapper macro for logging, which usually leads to an ugly macro bonanza.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;format&amp;gt;

void log(
    const std::string&amp;amp; message,
    const std::string&amp;amp; fileName = __FILE__,
    unsigned lineNo = __LINE__)
{
    std::cout &amp;lt;&amp;lt; std::format(
        &quot;{}({}): {}\n&quot;,
        fileName,
        lineNo,
        message);
}

#define LOG(msg) log(msg, __FILE__, __LINE__)

int main()
{
    log(&quot;hello world&quot;);
    // logs: example.cpp(7): hello world
    // Note that __FILE__ and __LINE__ are expanded at their
    // position, not at the callsite
    LOG(&quot;hello world2&quot;);
    // logs: example.cpp(22): hello world2
    // Wrapping the call in another macro with explicit placement
    // of __FILE__ and __LINE__ makes them expand at the correct place
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;C++20 introduces &lt;code&gt;std::source_location&lt;/code&gt;, a regular object that can be constructed as a default value of a logging function parameter and passed along as the user needs.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;source_location&amp;gt;
#include &amp;lt;format&amp;gt;

void log(
    const std::string&amp;amp; message,
    std::source_location location = std::source_location::current())
{
    std::cout &amp;lt;&amp;lt; std::format(
        &quot;{}({}) {}: {}\n&quot;,
        location.file_name(),
        location.line(),
        location.function_name(),
        message);
}

int main()
{
    log(&quot;hello world&quot;);
    // logs: example.cpp(19) int main(): hello world
}
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/15917/tuesday-coding-tip-09-source-location</guid>
<pubDate>Tue, 28 Apr 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 08 — Explicit template specialization</title>
<link>https://coderlegion.com/14710/tuesday-coding-tip-08-explicit-template-specialization</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;While template instantiation can be used to move your template implementation from header files to object files for a given subset of types, specialization allows you to override the default template implementation for a particular type.&lt;/p&gt;
&lt;p&gt;Specialization requires that you first define the template implementation and then you can implement any number of specializations for given types. This way, you can override free functions (while maintaining their overall signature) or you can override whole classes (and you don’t have to respect their interfaces). This way, you can create drop-in replacements for library containers specialized for particular types and try to optimize them for your use case.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;filesystem&amp;gt;
#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;

template&amp;lt;class T&amp;gt;
T concat(T a, const T&amp;amp; b)
{
    return a + b;
}

namespace fs = std::filesystem;

fs::path concat(fs::path a, const fs::path&amp;amp; b)
{
    return a / b;
}

int main()
{
    using namespace std::string_literals;
    std::cout &amp;lt;&amp;lt; concat(&quot;aaa&quot;s, &quot;bbb&quot;s) &amp;lt;&amp;lt; std::endl;        // outputs: aaabbb
    std::cout &amp;lt;&amp;lt; concat(&quot;aaa&quot;, &quot;bbb&quot;).string() &amp;lt;&amp;lt; std::endl; // outputs: aaa\bbb
    return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The specialization can also be partial and it can be &lt;code&gt;inline&lt;/code&gt;/&lt;code&gt;const&lt;/code&gt; whatever even if the original template is not.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;

template&amp;lt;class T&amp;gt;
struct CustomType
{
    T foo() { return T {}; }
};

template&amp;lt;&amp;gt;
struct CustomType&amp;lt;std::string&amp;gt;
{
    std::string bar() { return &quot;hello world&quot;; }
};

int main()
{
    CustomType&amp;lt;int&amp;gt; ct1;
    std::cout &amp;lt;&amp;lt; ct1.foo() &amp;lt;&amp;lt; std::endl; // outputs: 0
    CustomType&amp;lt;std::string&amp;gt; ct2;
    std::cout &amp;lt;&amp;lt; ct2.bar() &amp;lt;&amp;lt; std::endl; // outputs: &quot;hello world&quot;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Last but not least, if you’re implementing a template and need to change only a few lines of implementation for one particular type, you don’t need specialization. Instead, use &lt;code&gt;constexpr&lt;/code&gt; conditions — they are evaluated in compile time and optimized away when the compiler emits its own specialized code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;concepts&amp;gt;
#include &amp;lt;filesystem&amp;gt;
#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;

template&amp;lt;class T&amp;gt;
T concat(T a, const T&amp;amp; b)
{
    if constexpr (std::is_same_v&amp;lt;T, std::filesystem::path&amp;gt;)
        return a / b;
    else
        return a + b;
}

int main()
{
    using namespace std::string_literals;
    using path = std::filesystem::path;
    std::cout &amp;lt;&amp;lt; concat(&quot;aaa&quot;s, &quot;bbb&quot;s) &amp;lt;&amp;lt; std::endl; // outputs: aaabbb
    std::cout &amp;lt;&amp;lt; concat(path{ &quot;aaa&quot; }, path{ &quot;bbb&quot; }).string()
              &amp;lt;&amp;lt; std::endl; // outputs: aaa\bbb
    return 0;
}
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/14710/tuesday-coding-tip-08-explicit-template-specialization</guid>
<pubDate>Tue, 21 Apr 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 07 — Exposing internal bits of .NET projects</title>
<link>https://coderlegion.com/14709/tuesday-coding-tip-07-exposing-internal-bits-of-net-projects</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;C# has a number of visibility keywords and their combinations. A peculiar one is ‘internal’ which restricts the visibility of the symbols to the current assembly. However, that can be tweaked.&lt;/p&gt;
&lt;p&gt;You can manually specify the names of assemblies to which the ‘internal’ bits will be visible. Why is this useful? Because you can expose otherwise private parts of your code to assemblies like unit tests and test code with ease. No more ‘friend’ shenanigans like in C++ unit tests!&lt;/p&gt;
&lt;p&gt;Ways how to configure this evolved over the years and the most up-to-date approach seems to be in configuring the project file directly (with the latest MSVC and .NET 5+).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Project&amp;gt;
    &amp;lt;!-- ... ---&amp;gt;

 &amp;lt;ItemGroup&amp;gt;
  &amp;lt;AssemblyAttribute Include=&quot;System.Runtime.CompilerServices.InternalsVisibleTo&quot;&amp;gt;
   &amp;lt;_Parameter1&amp;gt;$(AssemblyName).Tests&amp;lt;/_Parameter1&amp;gt;
  &amp;lt;/AssemblyAttribute&amp;gt;
 &amp;lt;/ItemGroup&amp;gt;

&amp;lt;/Project&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/14709/tuesday-coding-tip-07-exposing-internal-bits-of-net-projects</guid>
<pubDate>Tue, 14 Apr 2026 11:49:31 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 06 - Explicit template instantiation</title>
<link>https://coderlegion.com/13658/tuesday-coding-tip-06-explicit-template-instantiation</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Templated code in C++ must be defined in the header files (or a function within the same &lt;code&gt;.cpp&lt;/code&gt; file). This is because whenever a templated function is called, the compiler generates a new implementation using the concrete type the function was called with. If you split the definition from the declaration, you need to tell it what implementations to generate and link.&lt;/p&gt;
&lt;p&gt;That’s what explicit template instantiation is for. It is useful when you’re writing generic code for a well-known subset of types, like string manipulation. It cannot be used for totally generic types because you need to be able to list all types the template will be used with (otherwise the user will get a linker error).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// .hpp
#pragma once

#include &amp;lt;string&amp;gt;
#include &amp;lt;concepts&amp;gt;

// Note me using constructible_from instead of is_same_v. This will
// get me into trouble
template&amp;lt;class T&amp;gt;
concept NarrowOrWideString = std::constructible_from&amp;lt;std::string, T&amp;gt;
|| std::constructible_from&amp;lt;std::wstring, T&amp;gt;;

template&amp;lt;NarrowOrWideString StringType&amp;gt;
StringType StrTransformation(StringType source);

template&amp;lt;NarrowOrWideString StringType&amp;gt;
class ClassTemplate
{
public:
    static StringType StrTransformation(StringType source);
};
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;// .cpp
template&amp;lt;NarrowOrWideString StringType&amp;gt;
StringType StrTransformation&amp;lt;StringType&amp;gt;(StringType source)
{
   /* some transformation */
   return source;
}

template std::string StrTransformation&amp;lt;std::string&amp;gt;(std::string);
template std::wstring StrTransformation&amp;lt;std::wstring&amp;gt;(std::wstring);


template&amp;lt;NarrowOrWideString StringType&amp;gt;
StringType ClassTemplate&amp;lt;StringType&amp;gt;::StrTransformation(StringType source)
{
   /* some transformation */
   return source;
}

template class ClassTemplate&amp;lt;std::string&amp;gt;;
template class ClassTemplate&amp;lt;std::wstring&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;// main.cpp
int main()
{
   {
      // This links, note the explicitly created string in parameters
      auto str = StrTransformation(std::string(&quot;aaa&quot;));
    
      auto wstr = StrTransformation(std::wstring(L&quot;bbb&quot;));
    
      // ERROR: Type does not conform to concept
      // auto num = StrTransformation(10);
    
      // ERROR: Type does conform to concept,
      // but template was not instantiated for const char[4]
      // auto str2 = StrTransformation(&quot;aaa&quot;);
    
      // This works, template overload was explicitly specified
      // and the concept allows conversion of const char* to std::string
      // Note that if I used is_same_v instead of constructible_from,
      // I couldn't use const char* as an argument.
      auto str3 = StrTransformation&amp;lt;std::string&amp;gt;(&quot;aaa&quot;);
    
      // Or I can make an alias
      constexpr auto&amp;amp;&amp;amp; StrTransformationA = StrTransformation&amp;lt;std::string&amp;gt;;
      auto str4 = StrTransformationA(&quot;aaa&quot;);
   }
  
   {
      // ERROR: C++ template type deduction is not good enough
      // auto str1 = ClassTemplate::StrTransformation(std::string(&quot;aaa&quot;));
    
      // I need to be explicit
      auto str2 = ClassTemplate&amp;lt;std::string&amp;gt;::StrTransformation(&quot;aaa&quot;);
    
      // Or make an alias
      using ClassTemplateA = ClassTemplate&amp;lt;std::string&amp;gt;;
      auto str3 = ClassTemplateA::StrTransformation(&quot;aaa&quot;);
   }
}
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/13658/tuesday-coding-tip-06-explicit-template-instantiation</guid>
<pubDate>Tue, 07 Apr 2026 09:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 05 - Object initialization in C++</title>
<link>https://coderlegion.com/13657/tuesday-coding-tip-05-object-initialization-in-c</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;There is a five-hundred-page book about C++ initialization out there. Why? Because we cater to way too many styles and many constructor capabilities. This tip is not about explaining all the options but rather about some good practices you can use to minimize mistakes.&lt;/p&gt;
&lt;p&gt;The “classic” or pre-C++11 way of initializing objects has the pitfall of triggering the “most vexing parse”. In such case, the compiler cannot tell whether you are calling a constructor or making a function declaration. And because C allowed for function declaration inside functions, it will pick the function declaration. You can omit the braces for the default constructor, but you can still encounter problems as shown in the ‘mvp2’ case. Trunk versions of GCC and Clang emit a helpful warning in this case.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Classic C++ style
Object obj1(param1, param2); // This works
Object mvp1(); // Most Vexing Parse
Object mvp2(int(param1), int(param2)); // Also MVP
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The “modern”, “universal” or post-C++11 way is also not the best one. It is consistent with struct initialization but can invoke incorrect constructors if you intermix normal parameters and &lt;code&gt;std::initializer_list&lt;/code&gt; as demonstrated with the &lt;code&gt;std::vector&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Modern (uniform) C++ style
Object obj2{param1, param2};
Object obj2_2 = {param1, param2};
std::vector&amp;lt;int&amp;gt; vec(10); // vector containing ten default constructed items
std::vector&amp;lt;int&amp;gt; vec{10}; // vector containing one element with value 10
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then you have what I call a “Java” style. It’s verbose and has the same issues if you use curly braces. At least it doesn’t trigger MVP. The last version is what I often use due to its similarity to many other languages where you use &lt;code&gt;var&lt;/code&gt; or &lt;code&gt;let&lt;/code&gt; to denote the variables and usually specify the type name after the variable name.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Verbose Java style
Object obj3 = Object(param1, param2);
Object obj3_2 = Object{param1, param2};

// Modern language style
auto obj4 = Object(param1, param2);
auto obj4_2 = Object{param1, param2};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that even though there is an assignment operator, no assignment, copy or move is happening — objects are constructed directly.&lt;/p&gt;
&lt;p&gt;I recommend using the “modern language style” with simple braces only for regular constructors and curly braces only for initializer-list constructors. It makes your intent clear and prevents you from accidentally shooting yourself in the foot. “Java style” might be preferable for class attribute declarations, with the same rules regarding braces.&lt;/p&gt;
&lt;p&gt;More on the subject:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.youtube.com/watch?v=7DTlWPgX6zs&quot;&gt;CppCon 2018: Nicolai Josuttis “The Nightmare of Initialization in C++” — YouTube&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://stackoverflow.com/questions/49802012/different-ways-of-initializing-an-object-in-c&quot;&gt;class — Different ways of initializing an object in c++ — Stack Overflow&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/13657/tuesday-coding-tip-05-object-initialization-in-c</guid>
<pubDate>Tue, 31 Mar 2026 09:26:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 04 - Precompiled headers</title>
<link>https://coderlegion.com/12876/tuesday-coding-tip-04-precompiled-headers</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Do you use CMake and need to improve your C++ compile times? There’s a technique called precompiled headers. Usually, it is somewhat obtuse to set up, MSVC tends to force you to include the precompiled header in every single &lt;code&gt;.cpp&lt;/code&gt; file.&lt;/p&gt;
&lt;p&gt;With CMake, you can use a single command to instantly boost your compile times with zero invasiveness. On my hobby project, I reduced compile time down from 3m30s to just 30s (in single threaded CI, I went from 7m to 3m30s).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# PROJECT_NAME refers to target that was used with
# add_library or add_executable command
target_precompile_headers ( ${PROJECT_NAME}
    PRIVATE
        &amp;lt;vector&amp;gt;
        &amp;lt;format&amp;gt;
        &amp;lt;map&amp;gt;
        &amp;lt;unordered_map&amp;gt;
        &amp;lt;array&amp;gt;
        &amp;lt;optional&amp;gt;
        &amp;lt;expected&amp;gt;
        &amp;lt;fstream&amp;gt;
        &amp;lt;filesystem&amp;gt;
        &amp;lt;functional&amp;gt;
        &amp;lt;concepts&amp;gt;
        &amp;lt;memory&amp;gt;
        &amp;lt;string&amp;gt;
        &amp;lt;cstdint&amp;gt;
        &amp;lt;DGM/dgm.hpp&amp;gt;
        &amp;lt;TGUI/tgui.hpp&amp;gt;
        &amp;lt;json.hpp&amp;gt;
)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Just remember to only include headers that don’t change often, presumably never. Good candidates are &lt;code&gt;std&lt;/code&gt; headers and third party header-only dependencies.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/12876/tuesday-coding-tip-04-precompiled-headers</guid>
<pubDate>Tue, 24 Mar 2026 10:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 03 - Structured bindings</title>
<link>https://coderlegion.com/12874/tuesday-coding-tip-03-structured-bindings</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Since C++17, we can use “structured bindings”. These allow you to perform tuple, array, or even structure unpacking. Such unpacking is commonly helpful when iterating over maps, so you don’t have to define an alias for key and value manually. It is equally useful when a function returns a tuple.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// Iterating over key-value pairs
auto myMap = std::unordered_map&amp;lt;std::string, int&amp;gt;{ /* ... */ };
for (auto&amp;amp;&amp;amp; [key, value] : myMap)
{ /* ... */ }

// Tuple unpacking
auto&amp;amp;&amp;amp; [index, quantity, name] = std::tuple{10, 30, &quot;a&quot;};

// Struct member aliasing
struct S {
    int veryLongAndDescriptiveName;
    std::string anotherVeryWordyName;
};

auto&amp;amp;&amp;amp; [index2, name2] = S{}; // s is of type S

// Array unpacking
auto&amp;amp;&amp;amp; [first, second, third] = std::array{1, 2, 3};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Unpacking struct members and arrays is just a cherry on top. You won’t use it much, but it is there should you ever need it!&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/12874/tuesday-coding-tip-03-structured-bindings</guid>
<pubDate>Tue, 17 Mar 2026 10:59:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 02 - Template with type-specific API</title>
<link>https://coderlegion.com/12272/tuesday-coding-tip-02-template-with-type-specific-api</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;What if you had a template class and you wanted to give it extra methods for certain specializations?&lt;/p&gt;
&lt;p&gt;For example, you might want to make a templated initialization guard and you want it to be as non-intrusive as possible. So you want it to support arithmetic operations if the underlying type is an arithmetic type.&lt;/p&gt;
&lt;p&gt;Before C++20, you could leverage &lt;code&gt;std::enable_if&lt;/code&gt;. However, such code is clunky and unreadable:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;type_traits&amp;gt;
#include &amp;lt;string&amp;gt;

// Pre C++20
template&amp;lt;class T&amp;gt;
class TemplatedClass
{
public:
  template&amp;lt;class = typename std::enable_if&amp;lt;std::is_integral&amp;lt;T&amp;gt;::value&amp;gt;::type&amp;gt;
  void foo() {}
};

int main()
{
  TemplatedClass&amp;lt;int&amp;gt; a;
  a.foo(); // OK

  TemplatedClass&amp;lt;std::string&amp;gt; b;
  b.foo(); /* Error:
  error: failed requirement 'std::is_integral&amp;lt;std::basic_string...&amp;gt;' requested here
  error: no matching member function for call to 'foo'
  note: candidate template ignored: couldn't infer template argument ''
  */
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With C++20, you can use concepts and the requires keyword to clean up the syntax significantly, either by in-place definition of type properties or by defining a dedicated concept. It also improves readability of error messages.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;type_traits&amp;gt;
#include &amp;lt;string&amp;gt;

// C++20, requires
template&amp;lt;class T&amp;gt;
class TemplatedClass2
{
public:
  template&amp;lt;typename = void&amp;gt;
  requires std::is_integral_v&amp;lt;T&amp;gt;
  void foo() {}
};

// C++20 with concept
template&amp;lt;class T&amp;gt;
concept IsIntegral = std::is_integral_v&amp;lt;T&amp;gt;;

template&amp;lt;class T&amp;gt;
class TemplatedClass3
{
public:
  template&amp;lt;typename = void&amp;gt;
  requires IsIntegral&amp;lt;T&amp;gt;
  void foo() {}
};

int main() {
  TemplatedClass2&amp;lt;int&amp;gt; a;
  a.foo(); // Ok

  TemplatedClass3&amp;lt;std::string&amp;gt; b;
  b.foo(); /* Error:
  error: no matching member function for call to 'foo'
  note: candidate template ignored: constraints not satisfied [with $0 = void]
  note: because 'std::basic_string&amp;lt;char&amp;gt;' does not satisfy 'IsIntegral'
  note: because 'std::is_integral_v&amp;lt;std::basic_string&amp;lt;char&amp;gt; &amp;gt;' evaluated to false
  */
}
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/12272/tuesday-coding-tip-02-template-with-type-specific-api</guid>
<pubDate>Tue, 10 Mar 2026 11:00:00 +0000</pubDate>
</item>
<item>
<title>Tuesday Coding Tip 01 - C++ Concepts</title>
<link>https://coderlegion.com/12271/tuesday-coding-tip-01-c-concepts</link>
<description>&lt;p&gt;Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Concepts are a C++20 feature that greatly simplifies templated code and allows you to build powerful type trait restrictions.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;concepts&amp;gt;

class Interface {
public:
    ~Interface() = default;
};

template&amp;lt;class T&amp;gt;
concept DerivedFromInterface = std::derived_from&amp;lt;T, Interface&amp;gt;;

// Note how 'class' or 'typename' is replaced with 'DerivedFromInterface'
template&amp;lt;DerivedFromInterface ObjectType&amp;gt;
void DoSomethingWith(ObjectType&amp;amp; object) {}

// Usage
class A final : public Interface {};
A a;
DoSomethingWith(a);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For example, you can create a function that accepts a concrete type that implements a certain interface, potentially allowing the compiler to optimize away the virtual table. Or you can define static interfaces where an object is required to have certain methods or even attributes, even if it doesn’t implement any inheritance-based interface. Or you can restrict the function to be called only with a small subset of well-known types.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;concepts&amp;gt;
#include &amp;lt;string&amp;gt;

template&amp;lt;class T&amp;gt;
concept Serializable = requires(T&amp;amp;&amp;amp; object)
{
    // Object has callable method 'serialize' which
    // returns something that works same as std::string
    { object.serialize()} -&amp;gt; std::same_as&amp;lt;std::string&amp;gt;;
};

template&amp;lt;Serializable T&amp;gt;
void UploadSerializable(const T&amp;amp; object)
{
    auto data = object.serialize();
    // ...
}

// Usage
class Settings {
public:
    std::string serialize() const { return &quot;&quot;; }
};

Settings settings;
UploadSerializable(settings);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Concepts do not replace dynamic polymorphism as you cannot do everything in compile-time. Still, it can open new optimization opportunities and help you write in-place construction functions like &lt;code&gt;std::make_unique&lt;/code&gt; without an excessive amount of unreadable templates.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;concepts&amp;gt;
#include &amp;lt;string&amp;gt;
#include &amp;lt;memory&amp;gt;

// A function that accepts any string, disregarding if wide or narrow
template&amp;lt;typename T&amp;gt;
requires std::is_same_v&amp;lt;T, std::string&amp;gt; || std::is_same_v&amp;lt;T, std::wstring&amp;gt;
void DoSomethingWithAString(const T&amp;amp; str) {}

// A better implementation of make_unique which checks whether the
// object can be created from given arguments
template&amp;lt;class T, class ... Args&amp;gt;
requires std::constructible_from&amp;lt;T, Args...&amp;gt;
std::unique_ptr&amp;lt;T&amp;gt; make_unique(Args&amp;amp;&amp;amp; ... args)
{
    return std::unique_ptr&amp;lt;T&amp;gt;(new T(std::forward&amp;lt;Args&amp;gt;(args)...));
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Lastly, among the benefits to the syntax, they improve the compiler error messages, making life of your users way simpler.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/12271/tuesday-coding-tip-01-c-concepts</guid>
<pubDate>Tue, 03 Mar 2026 11:00:00 +0000</pubDate>
</item>
</channel>
</rss>