<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title>Articles tagged cpp at Royyan Dzakiy</title>
  <link rel="alternate" type="text/html"
        href="https://royyandzakiy.com/tags/cpp/"/>
  <link rel="self" type="application/atom+xml"
        href="https://royyandzakiy.com/tags/cpp/feed/"/>
  <updated>2026-10-16T09:06:07Z</updated>
  <id>urn:uuid:bdc867e4-b8f7-4cf0-8437-adafc8297129</id>

  <author>
    <name>Royyan Dzakiy</name>
    <uri>https://royyandzakiy.com</uri>
  </author>

  <entry>
    <title>Lefticus - C++ Project Template</title>
    <link rel="alternate" type="text/html" href="https://royyandzakiy.com/blog/2026-04/lefticus-cmake-project-template/"/>
    <id>urn:uuid:680e28b1-8f06-5e3a-93cd-eafac72086c7</id>
    <updated>2026-04-06T00:00:00Z</updated>
    <category term="cpp"/>
    <content type="html">
      <![CDATA[<p>I have been slowly adding more stuff for my complete <a href="https://github.com/royyandzakiy/cpp-project-template">@royyandzakiy/cpp-project-template</a>. Lately I’ve been focusing on adding things to do in the CI, and I was re-watching Jason’s video on HIS version of C++ project template.</p>

<div class="video-container">
  <iframe src="https://www.youtube.com/embed/YbgH7yat-Jo" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="">
  </iframe>
</div>

<p>Based on the video, here is a list of all the tools, libraries, and features that are used, added to, or used along with the cpp_starter_project:</p>

<p>Build &amp; Configuration Tools:</p>

<ul>
  <li>CMake</li>
  <li>CTest</li>
  <li>Conan (package manager)</li>
  <li>CCache</li>
</ul>

<p>Code Quality &amp; Formatting Tools:</p>

<ul>
  <li>clang-format</li>
  <li>cmake-format</li>
  <li>clang-tidy</li>
  <li>CPPCheck</li>
</ul>

<p>Compilers &amp; Sanitizers:</p>

<ul>
  <li>GCC / Clang / MSVC support</li>
  <li>Address Sanitizer</li>
  <li>Undefined Behavior Sanitizer</li>
  <li>Thread Sanitizer</li>
  <li>Fuzzing Sanitizer (libFuzzer from Clang/LLVM)</li>
</ul>

<p>Libraries (managed via Conan):</p>

<ul>
  <li>Catch2 (testing framework)</li>
  <li>docopt (command-line option parsing)</li>
  <li>fmt (formatting library, now partly in C++20)</li>
  <li>spdlog (fast logging)</li>
  <li>imgui-sfml (for IMGUI example)</li>
  <li>SFML (pulled in by imgui-sfml)</li>
  <li>SDL (for SDL example)</li>
</ul>

<p>Documentation:</p>

<ul>
  <li>Doxygen</li>
</ul>

<p>Example GUI Libraries Shown:</p>

<ul>
  <li>Qt</li>
  <li>FLTK</li>
  <li>GTKMM</li>
  <li>IMGUI</li>
  <li>NANA</li>
  <li>SDL</li>
</ul>

<p>Editors/IDEs Mentioned:</p>

<ul>
  <li>Neovim (with Neoformat plugin)</li>
</ul>

<p>Other Features:</p>

<ul>
  <li>Inter-procedural optimization (IPO) / Link Time Optimization (LTO)</li>
  <li>Precompiled headers (PCH)</li>
  <li>compile_commands.json generation (for clang tooling)</li>
  <li>Warnings as errors (-Werror / /WX)</li>
</ul>
]]>
    </content>
  </entry>
  <entry>
    <title>Zephyr Modern C++ - State Machine Size Comparison</title>
    <link rel="alternate" type="text/html" href="https://royyandzakiy.com/blog/2026-01/zephyr-cpp-vs-c-size/"/>
    <id>urn:uuid:0d1c8e4a-824d-5071-81bd-ab33d7526662</id>
    <updated>2026-01-12T00:00:00Z</updated>
    <category term="zephyr"/><category term="cpp"/><category term="statemachine"/>
    <content type="html">
      <![CDATA[<p>Can we use the latest C++ features on microcontrollers? <strong>Yes.</strong></p>

<p>I’ve been testing out to use it on Zephyr and ESP-IDF.</p>

<p>One particular feature I tried out in this example is the use of <code>std::variant</code> for different States, and ultimately using <code>std::visit</code> to iterate through them. Here I provide implementation of a general <code>get_state_info</code> to read what the current state is using the Overloaded Lambda idiom (to enforce availability of all StateVariants), it will then return a <code>std::string_view</code> of different messages based on the <code>current_state_</code>.</p>

<p>Let’s say, a more shiny StateMachine haha. A different approach than using bare enums and switch statements (not simply saying they are less).</p>

<p>Check it out!
<a href="https://github.com/royyandzakiy/zephyr-modern-cpp">https://github.com/royyandzakiy/zephyr-modern-cpp</a></p>

<!--more-->

<p>So far, there is a <strong>540 bytes difference</strong> when using <code>std::variant</code>/<code>std::visit</code>, compared to raw enum/switch.</p>

<p><strong>First build (std::variant/visit):</strong></p>
<ul>
  <li>FLASH: 73,112 bytes (6.97% of 1MB)</li>
  <li>RAM: 53,928 bytes (11.76% of 448KB)</li>
</ul>

<p><strong>Second build (enum/switch)</strong> (code depicted in image below):</p>
<ul>
  <li>FLASH: 72,572 bytes (6.92% of 1MB)</li>
  <li>RAM: 53,928 bytes (11.76% of 448KB)</li>
</ul>

<p>I also tried comparing when adding the C++ library to the compilation, and removing it. There is a <strong>4256 byte addition</strong>.</p>

<p><strong>Third build</strong> (converting all C++ to pure C &amp; but still compiling C++ library in kconfig):</p>
<ul>
  <li>FLASH: 71,588 bytes (6.83% of 1MB)</li>
  <li>RAM: 53,952 bytes (11.76% of 448KB)</li>
</ul>

<p><strong>Fourth build</strong> (converting all C++ to pure C &amp; removing C++ library in kconfig):</p>
<ul>
  <li>FLASH: 67,332 bytes (6.42% of 1MB)</li>
  <li>RAM: 53,840 bytes (11.74% of 448KB)</li>
</ul>

<p><strong>State machine using std::variant, std::visit</strong></p>

<p><img src="/assets/images/zephyr-cpp-vs-c-size_variant.png" alt="alt text" /></p>

<p><strong>State machine using enum &amp; switch</strong></p>

<p><img src="/assets/images/zephyr-cpp-vs-c-size_switch.png" alt="alt text" /></p>

<p><strong>Removing most all CPP code, change into C</strong></p>

<p><img src="/assets/images/zephyr-cpp-vs-c-size_c_cpp.png" alt="alt text" /></p>

<p><strong>Removing CPP lib in prj.conf</strong></p>

<p><img src="/assets/images/zephyr-cpp-vs-c-size_pure_c.png" alt="alt text" /></p>

<p><strong>Code using enum &amp; switch</strong></p>

<p><img src="/assets/images/zephyr-cpp-vs-c-size_recode_pure_c.png" alt="alt text" /></p>

<hr />

<p>The variant doesn’t add too much overhead. I was expecting a lot more bytes eaten up just by using Templates itself 😄</p>

<p>cc Srdjan Stokic</p>
]]>
    </content>
  </entry>
  <entry>
    <title>Compiling latest Clang++</title>
    <link rel="alternate" type="text/html" href="https://royyandzakiy.com/blog/2025-12/latest-clang-compile/"/>
    <id>urn:uuid:cd803713-157d-58af-8199-105836dfe0f2</id>
    <updated>2025-12-29T00:00:00Z</updated>
    <category term="cpp"/>
    <content type="html">
      <![CDATA[<p>Just finished my 4 hr compile (with many many times failing) of the llvm-project to get the latest clang++ with custom features 😅</p>

<p>Compiled it in Linux WSL</p>

<p>Here Mike explained the steps very well through his youtube video “
Build Clang++20 (LLVM 18 and lldb) from source”</p>

<div class="video-container">
  <iframe src="https://www.youtube.com/embed/LbhGPiGI_Qs" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="">
  </iframe>
</div>

<p>And the guide in the Clang website is surprisingly good to get started
<a href="https://clang.llvm.org/get_started.html">LLVM - Getting Started: Building and Running Clang</a></p>
]]>
    </content>
  </entry>
  <entry>
    <title>Zephyr Modern C++ - Sensors Concept</title>
    <link rel="alternate" type="text/html" href="https://royyandzakiy.com/blog/2025-12/zephyr-sensors-concept/"/>
    <id>urn:uuid:e597f402-7f2e-5098-beae-74797c9122b0</id>
    <updated>2025-12-23T00:00:00Z</updated>
    <category term="cpp"/>
    <content type="html">
      <![CDATA[<p>Can we use the latest c++ features on microcontrollers? I’ve been testing out to use it on Zephyr and ESP-IDF</p>

<p>Here is the continuation of the last post.</p>

<p>This time I try using Concepts to iterate through a bunch of “Sensors”. Here I use the generic function process_sensors that utilizes C++ Template Metaprogramming and uses the Ellipsis “…” operator to process through an arbritary amount of sensors (in this case, 3). The result is an expressive and elegant code (feels like I’m coding in javascript with the Spread Operator haha).</p>

<p>The measurements array stores results of read() of each sensors, invoked each time this process_sensors gets called. Fun fact, here the std::array automatically deduces it’s own type and size because of Class Template Argument Deduction (CTAD) enforced by the SensorLike concept (no need to define std::array&lt;type, size&gt;).</p>

<p>Is it the most efficient in the case when we need to optimize for firmware size, probably not. Is it fun? Yesh</p>

<p>Check it out!</p>

<p><a href="https://github.com/royyandzakiy/zephyr-modern-cpp">github.com/royyandzakiy/zephyr-modern-cpp</a></p>

<pre class="highlight"><code><span class="c">// --- Concepts &amp; Constraints ---</span>
<span class="k">template</span> &lt;<span class="k">typename</span> <span class="t">T</span>&gt;
<span class="k">concept</span> <span class="t">SensorLike</span> = <span class="k">requires</span>(<span class="t">T</span> t) {
	{ t.read() } -&gt; std::convertible_to&lt;<span class="t">int32_t</span>&gt;;
	{ t.get_id() } -&gt; std::convertible_to&lt;<span class="t">int</span>&gt;;
};

<span class="c">// --- Sensor Concepts Implementation ---</span>
<span class="k">class</span> <span class="t">TemperatureSensor</span> {
  <span class="k">public</span>:
	<span class="k">auto</span> read() <span class="k">const</span> -&gt; <span class="t">int32_t</span> {
		<span class="k">return</span> <span class="m">2350</span> + (sys_rand32_get() % <span class="m">100</span>); <span class="c">// 23.50 – 24.49</span>
	}
	<span class="k">auto</span> get_id() <span class="k">const</span> -&gt; <span class="t">int</span> {
		<span class="k">return</span> <span class="m">1</span>;
	}
};

<span class="k">class</span> <span class="t">HumiditySensor</span> {
  <span class="k">public</span>:
	<span class="k">auto</span> read() <span class="k">const</span> -&gt; <span class="t">int32_t</span> {
		<span class="k">return</span> <span class="m">4500</span> + (sys_rand32_get() % <span class="m">200</span>); <span class="c">// 45.00 – 46.99</span>
	}
	<span class="k">auto</span> get_id() <span class="k">const</span> -&gt; <span class="t">int</span> {
		<span class="k">return</span> <span class="m">2</span>;
	}
};

<span class="k">class</span> <span class="t">PressureSensor</span> {
  <span class="k">public</span>:
	<span class="k">auto</span> read() <span class="k">const</span> -&gt; <span class="t">int32_t</span> {
		<span class="k">return</span> <span class="m">101325</span> + (sys_rand32_get() % <span class="m">500</span>); <span class="c">// 1013.25+</span>
	}
	<span class="k">auto</span> get_id() <span class="k">const</span> -&gt; <span class="t">int</span> {
		<span class="k">return</span> <span class="m">3</span>;
	}
};

<span class="k">class</span> <span class="t">StateMachine</span> {
    <span class="c">// ...</span>
    <span class="k">template</span> &lt;<span class="t">SensorLike</span>... <span class="t">Sensors</span>&gt; <span class="k">auto</span> process_sensors(<span class="t">Sensors</span> &amp;&amp;...sensors) -&gt; <span class="t">void</span> {
		<span class="k">const</span> std::array measurements{sensors.read()...};
		<span class="t">int</span> temperatureSensorIdx = <span class="m">0</span>;

		<span class="c">// all sensor logic</span>
		{
			<span class="t">int</span> sensorIdx = <span class="m">0</span>;
			(
				[&amp;]&lt;<span class="k">typename</span> <span class="t">T</span>&gt;(<span class="t">T</span> &amp;sensor) {
					<span class="k">const</span> <span class="t">char</span> *label = <span class="s">"Unknown"</span>;
					<span class="k">if</span> <span class="k">constexpr</span> (std::is_same_v&lt;<span class="t">T</span>, <span class="t">TemperatureSensor</span>&gt;) {
						label = <span class="s">"Temp"</span>;
						temperatureSensorIdx = sensorIdx;
					}
					<span class="k">if</span> <span class="k">constexpr</span> (std::is_same_v&lt;<span class="t">T</span>, <span class="t">HumiditySensor</span>&gt;)
						label = <span class="s">"Humid"</span>;
					<span class="k">if</span> <span class="k">constexpr</span> (std::is_same_v&lt;<span class="t">T</span>, <span class="t">PressureSensor</span>&gt;)
						label = <span class="s">"Press"</span>;

					LOG_INF(<span class="s">"Sensor: %s | Value: %d"</span>, label, measurements[sensorIdx++]);
				}(sensors),
				...);
		}

		<span class="c">// TemperatureSensor value will cause system State change</span>
		{
			<span class="k">const</span> <span class="t">int32_t</span> latest_temp = measurements[<span class="m">0</span>];
			<span class="k">const</span> <span class="t">size_t</span> stored_count = std::min(buffer_index_, temp_data_circbuf_.size());

			<span class="c">// Update circular buffer</span>
			temp_data_circbuf_[buffer_index_ % temp_data_circbuf_.size()] = latest_temp;
			buffer_index_++;

			std::visit(
				[<span class="k">this</span>, latest_temp, stored_count]&lt;<span class="k">typename</span> <span class="t">Traw</span>&gt;(<span class="t">Traw</span> &amp;state) {
					<span class="k">using</span> <span class="t">T</span> = std::<span class="t">decay_t</span>&lt;<span class="t">Traw</span>&gt;; <span class="c">// cleanup any const/refs</span>

					<span class="c">// this way, enforcement to ensure all Variant types are covered by the compiler becomes optional</span>
					<span class="c">// (else, via static_assert). if I ommit the else, we can have a non-exhaustive "state machine"</span>
					<span class="k">if</span> <span class="k">constexpr</span> (std::is_same_v&lt;<span class="t">T</span>, <span class="t">IdleState</span>&gt;) {
						<span class="k">if</span> (latest_temp &gt; TEMP_THRESHOLD_START_MONITORING) {
							transition_to(<span class="t">MonitoringState</span>{latest_temp, <span class="m">1</span>});
						}
					} <span class="k">else</span> <span class="k">if</span> <span class="k">constexpr</span> (std::is_same_v&lt;<span class="t">T</span>, <span class="t">MonitoringState</span>&gt;) {
						state.sample_count++;

						<span class="k">auto</span> sum =
							std::accumulate(temp_data_circbuf_.begin(), temp_data_circbuf_.begin() + stored_count, <span class="m">0LL</span>);

						state.average_temp_value = <span class="k">static_cast</span>&lt;<span class="t">int32_t</span>&gt;(sum / stored_count);

						<span class="k">if</span> (state.average_temp_value &gt; TEMP_THRESHOLD_ALERT) {
							transition_to(<span class="t">AlertState</span>{<span class="s">"Temperature High"</span>sv, TEMP_THRESHOLD_ALERT});
						}
					} <span class="k">else</span> <span class="k">if</span> <span class="k">constexpr</span> (std::is_same_v&lt;<span class="t">T</span>, <span class="t">AlertState</span>&gt;) {
						<span class="k">if</span> (latest_temp &lt; TEMP_THRESHOLD_RECOVERY) {
							transition_to(<span class="t">CalibratingState</span>{CALIBRATION_REFERENCE_TEMP, <span class="m">1</span>});
						}
					} <span class="k">else</span> <span class="k">if</span> <span class="k">constexpr</span> (std::is_same_v&lt;<span class="t">T</span>, <span class="t">CalibratingState</span>&gt;) {
						<span class="k">if</span> (++state.calibration_step &gt; MAX_CALIBRATION_STEPS) {
							transition_to(<span class="t">IdleState</span>{});
						}
					} <span class="k">else</span> <span class="k">if</span> <span class="k">constexpr</span> (std::is_same_v&lt;<span class="t">T</span>, std::monostate&gt;) {
						transition_to(<span class="t">IdleState</span>{});
					} <span class="k">else</span> {
						<span class="c">// C++23: If a new state is added to StateVariant but not handled yet, force compile error</span>
						<span class="k">static_assert</span>(uncovered_type_exists&lt;<span class="t">T</span>&gt;,
									  <span class="s">"Non-exhaustive visitor: You forgot to handle a state!"</span>);
					}
				},
				current_state_);
		}
	}
};

<span class="k">auto</span> main() -&gt; <span class="t">int</span> {
    <span class="t">StateMachine</span> sm_;
	<span class="t">TemperatureSensor</span> t_;
	<span class="t">HumiditySensor</span> h_;
	<span class="t">PressureSensor</span> p_;

    sm_.process_sensors(t_, h_, p_);

    <span class="k">return</span> <span class="m">0</span>;
}
</code></pre>
]]>
    </content>
  </entry>
  <entry>
    <title>Zephyr Modern C++ - Statemachines using std::variant/std::visit</title>
    <link rel="alternate" type="text/html" href="https://royyandzakiy.com/blog/2025-12/zephyr-statemachine-variant/"/>
    <id>urn:uuid:b67eda4b-206a-5830-bd89-1371e2b08a7f</id>
    <updated>2025-12-22T00:00:00Z</updated>
    <category term="cpp"/>
    <content type="html">
      <![CDATA[<p>Can we use the latest C++ features on microcontrollers? Yes.</p>

<p>I’ve been testing out to use it on Zephyr and ESP-IDF</p>

<p>One particular feature I tried out in this example is the use of std::variant for different States, and ultimately using std::visit to iterate through them. Here I provide implementation of a general get_state_info to read what the current state is using the Overloaded Lambda idiom (to enforce availability of all StateVariants), it will then return a std::string_view of different messages based on the current_state_</p>

<p>Let’s say, a more shiny Statemachine haha. A different approach than using bare enums and switch statements (not simply saying they are less)</p>

<p>Check it out here!</p>

<p><a href="https://github.com/royyandzakiy/zephyr-modern-cpp">github.com/royyandzakiy/zephyr-modern-cpp</a></p>

<pre class="highlight"><code><span class="k">enum</span> <span class="k">class</span> <span class="t">StateId</span> {
	IDLE,
	MONITORING,
	ALERT,
	CALIBRATING
};
<span class="k">struct</span> <span class="t">IdleState</span> {};
<span class="k">struct</span> <span class="t">MonitoringState</span> {
	<span class="t">int32_t</span> average_temp_value;
	<span class="t">int</span> sample_count;
};

<span class="k">struct</span> <span class="t">AlertState</span> {
	std::string_view message;
	<span class="t">int32_t</span> threshold_temp_value;
};

<span class="k">struct</span> <span class="t">CalibratingState</span> {
	<span class="t">int32_t</span> reference_temp_value;
	<span class="t">int</span> calibration_step;
};

<span class="k">using</span> <span class="t">StateVariant</span> = std::variant&lt;std::monostate, <span class="t">IdleState</span>, <span class="t">MonitoringState</span>, <span class="t">AlertState</span>, <span class="t">CalibratingState</span>&gt;;

<span class="k">class</span> <span class="t">StateMachine</span> {
    <span class="c">// ...</span>
    <span class="k">auto</span> get_state_info() <span class="k">const</span> -&gt; std::string_view {
		<span class="k">return</span> std::visit(<span class="t">Overloaded</span>{
			[<span class="k">this</span>](<span class="k">const</span> <span class="t">IdleState</span>&amp;) -&gt; std::string_view {
				<span class="k">return</span> <span class="s">"Status: Idle - Awaiting for sensor trigger"</span>sv;
			},
			[<span class="k">this</span>](<span class="k">const</span> <span class="t">MonitoringState</span>&amp; s) -&gt; std::string_view {
				<span class="c">// psst: not using std::format because the zephyr SDK does not have #include &lt;format&gt;</span>
				<span class="t">int</span> len = snprintf(format_buffer_.data(), format_buffer_.size(), 
									<span class="s">"Status: Monitoring [Avg: %d.%02d°C | Samples: %d]"</span>,
									ipart(s.average_temp_value), fpart(s.average_temp_value), s.sample_count);
				<span class="k">return</span> { format_buffer_.data(), <span class="k">static_cast</span>&lt;<span class="t">size_t</span>&gt;(len) };
			},
			[<span class="k">this</span>](<span class="k">const</span> <span class="t">AlertState</span>&amp; s) -&gt; std::string_view {
				<span class="t">int</span> len = snprintf(format_buffer_.data(), format_buffer_.size(), 
								<span class="s">"Status: ALERT [%.*s | Threshold: %d.%02d°C]"</span>, 
								<span class="k">static_cast</span>&lt;<span class="t">int</span>&gt;(s.message.length()), s.message.data(),
								ipart(s.threshold_temp_value), fpart(s.threshold_temp_value));
				<span class="k">return</span> {format_buffer_.data(), <span class="k">static_cast</span>&lt;<span class="t">size_t</span>&gt;(len)};
			},
			[<span class="k">this</span>](<span class="k">const</span> <span class="t">CalibratingState</span>&amp; s) -&gt; std::string_view {
				<span class="t">int</span> len = snprintf(format_buffer_.data(), format_buffer_.size(), 
								<span class="s">"Status: Calibrating [Ref: %d.%02d°C | Step: %d/5]"</span>, 
								ipart(s.reference_temp_value), fpart(s.reference_temp_value), s.calibration_step);
				<span class="k">return</span> {format_buffer_.data(), <span class="k">static_cast</span>&lt;<span class="t">size_t</span>&gt;(len)};
			},
			[<span class="k">this</span>](<span class="k">const</span> <span class="k">auto</span>&amp;) -&gt; std::string_view {
				<span class="c">// default fallback</span>
				<span class="k">return</span> <span class="s">"Status: Unknown State! [Error]"</span>sv;
			}
		}, current_state_);
	}
    <span class="c">// ...</span>
};

<span class="k">auto</span> main() -&gt; <span class="t">int</span> {
    <span class="t">StateMachine</span> sm_;
	<span class="t">TemperatureSensor</span> t_;
	<span class="t">HumiditySensor</span> h_;
	<span class="t">PressureSensor</span> p_;
    
    sm_.process_sensors(t_, h_, p_);

    <span class="c">// ...</span>

    <span class="k">auto</span> info = sm_.get_state_info();

    <span class="k">return</span> <span class="m">0</span>;
}
</code></pre>
]]>
    </content>
  </entry>
  <entry>
    <title>Perfect Forwarding the "Hello World!"</title>
    <link rel="alternate" type="text/html" href="https://royyandzakiy.com/blog/2025-12/hello-world/"/>
    <id>urn:uuid:55fd57bb-539e-5983-80b2-ad60fb6ca2b2</id>
    <updated>2025-12-20T00:00:00Z</updated>
    <category term="cpp"/>
    <content type="html">
      <![CDATA[<p>I’ve been going back and forth understanding lvalue and rvalue. Here is an attempt of mine in explaining it</p>

<p>So here is a cool “Perfect Forwarding” <code>Hello, World!</code> code implementation using C++. When <code>std::string{"World!"}</code> is passed, this is a prvalue (a “temporary”) aka an rvalue expression. <code>T</code> is deduced to <code>std::string</code>, becoming <code>say_hello(std::string &amp;&amp; name_param)</code>. In the other case, when instead the variable name is passed, this is a variable aka an lvalue, <code>T</code> is deduced to <code>std::string&amp;</code> becoming <code>say_hello(std::string&amp; &amp;&amp; name_param)</code>, the <code>&amp;&amp;</code> will get reduced (reference collapsing rules), therefore finally becoming <code>say_hello(std::string&amp; name_param)</code>.</p>

<p><code>std::forward&lt;T&gt;</code> restores the value category (lvalue/rvalue) of the original argument expression by conditionally casting the named parameter to the value category encoded in T, hence “Perfect Forwarding” (same type, same cv-qualification, same value category).</p>

<pre class="highlight"><code><span class="p">#include</span> <span class="s">&lt;print&gt;</span> 
<span class="p">#include</span> <span class="s">&lt;string&gt;</span>
<span class="p">#include</span> <span class="s">&lt;utility&gt;</span>

<span class="k">template</span> &lt;<span class="k">typename</span> <span class="t">T</span>&gt;
<span class="t">void</span> <span class="f">say_hello</span>(<span class="t">T</span>&amp;&amp; name_param) {
   std::println(<span class="s">"Hello, {}"</span>, std::forward&lt;<span class="t">T</span>&gt;(name_param)); 
}

<span class="t">int</span> <span class="f">main</span>() { 
    say_hello(std::string{<span class="s">"World!"</span>}); 
    
    std::string name = <span class="s">"Matt!"</span>;
    say_hello(name); 
  
    <span class="k">return</span> <span class="m">0</span>; 
}
</code></pre>
]]>
    </content>
  </entry>
  <entry>
    <title>Concepts in C++</title>
    <link rel="alternate" type="text/html" href="https://royyandzakiy.com/blog/2025-12/concepts/"/>
    <id>urn:uuid:baf5e3c2-6677-5421-ab74-2976079bbc63</id>
    <updated>2025-12-17T00:00:00Z</updated>
    <category term="cpp"/>
    <content type="html">
      <![CDATA[<p>Last post I shared about type traits to enable a SFINAE Class Template based Mocking to be used in the case of populating unit tests in cpp. Since C++20, the feature <code>Concept</code> is born. We will see how it is used in the code below, but my take on this is it’s essentially a more syntacticly nice Type Trait. But most importantly is, it has a better built in Error message (SFINAE errors are horrendeus imo)</p>

<p>In this example, I use a DigitalInput that will be used by a Button class (a study case of Embedded Systems). Here I assume the DigitalInput is some sort of given class from an library that we cannot modify, hence we would like to replace it with a Mock to enable non-HIL (Hardware in The Loop) tests. So I created a Concept <code>DigitalInputLike</code> that gets satisfied IFF any type has the <code>init()</code> and <code>read()</code> function in them. I also made an example of a BAD DigitalInput Mock that does not have the required functions, it will spit out a compilation error (nice catch concepts!)</p>

<p>During coding, the difference between using Type Traits compared to using Concepts is we do not need to have an addition of <code>typename std::enable_if_t</code> in the template typename call of the Button class. We also replace the use of typename with DigitalInputLike, and that automatically functions as a constraint.</p>

<pre class="highlight"><code><span class="p">#include</span> <span class="s">&lt;concepts&gt;</span>
<span class="p">#include</span> <span class="s">&lt;print&gt;</span>

<span class="c">// DigitalInputLike Concept</span>
<span class="k">template</span> &lt;<span class="k">typename</span> <span class="t">T</span>&gt;
<span class="k">concept</span> <span class="t">DigitalInputLike</span> = <span class="k">requires</span>(<span class="t">T</span> t) {
	{ t.init() } -&gt; std::same_as&lt;<span class="t">void</span>&gt;;
	{ t.read() } -&gt; std::convertible_to&lt;<span class="t">int</span>&gt;;
};

<span class="c">// Button Class Template (Uses Concept to Constrain it's instantiation)</span>
<span class="k">template</span>&lt;<span class="t">DigitalInputLike</span> <span class="t">T</span>&gt;
<span class="k">class</span> <span class="t">Button</span> {
<span class="k">public</span>:
	<span class="t">Button</span> (<span class="t">T</span>* input): m_DigitalInput(input) {}
	<span class="t">void</span> init() {
		m_DigitalInput-&gt;init();
		<span class="c">// rest of logic...</span>
	}
	<span class="t">int</span> read() {
		<span class="k">return</span> m_DigitalInput-&gt;read();
	}
<span class="k">private</span>:
	<span class="t">T</span> *m_DigitalInput;
};

<span class="c">// Digital Input (Real)</span>
<span class="k">class</span> <span class="t">DigitalInput</span> { 
<span class="k">public</span>:
	<span class="t">void</span> init();
	<span class="t">int</span> read();
	<span class="t">int</span> process();
};

<span class="c">// Digital Input (Good Mock)</span>
<span class="k">class</span> <span class="t">DigitalInputMock</span> { 
<span class="k">public</span>:
	<span class="t">void</span> init();
	<span class="t">int</span> read();
};

<span class="c">// Digital Input (Bad Mock)</span>
<span class="k">class</span> <span class="t">DigitalInputMock_Bad</span> { 
<span class="k">public</span>:
	<span class="c">/* void init();  */</span> <span class="c">// init() missing!</span>
	<span class="t">int</span> not_read(); 	<span class="c">// read() missing!</span>
};

<span class="k">auto</span> main() -&gt; <span class="t">int</span> {
	std::println(<span class="s">"Real Digital Input, will proceed successfully"</span>);
	<span class="t">DigitalInput</span> digitalInput;
    <span class="t">Button</span>&lt;<span class="t">DigitalInput</span>&gt; buttonWithReal(&amp;digitalInput); <span class="c">// succeed</span>

	std::println(<span class="s">"Good Mock, will proceed successfully"</span>);
	<span class="t">DigitalInputMock</span> digitalInputMock;
    <span class="t">Button</span>&lt;<span class="t">DigitalInputMock</span>&gt; buttonWithMock(&amp;digitalInputMock); <span class="c">// succeed</span>
	
	std::println(<span class="s">"Bad Mock, will fail to compile if run"</span>);
	<span class="t">DigitalInputMock_Bad</span> digitalInputBad;
    <span class="t">Button</span>&lt;<span class="t">DigitalInputMock_Bad</span>&gt; buttonWithBadMock(&amp;digitalInputBad); <span class="c">// SFINAE in action! Compile error</span>

	<span class="k">return</span> <span class="m">0</span>;
}
</code></pre>

<h2 id="output">Output</h2>

<p>(x86-64 clang 21.1.0 <code>-std=c++23</code>):</p>

<pre class="highlight"><code>&lt;<span class="k">source</span>&gt;:60:5: error: constraints not satisfied <span class="k">for</span> class template <span class="s">'Button'</span> [with T = DigitalInputMock_Bad]
   60 |     Button&lt;DigitalInputMock_Bad&gt; buttonWithBadMock(&amp;digitalInputBad); // SFINAE <span class="k">in</span> action! Compile error
      |     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
&lt;<span class="k">source</span>&gt;:12:10: note: because <span class="s">'DigitalInputMock_Bad'</span> does not satisfy <span class="s">'DigitalInputLike'</span>
   12 | template&lt;DigitalInputLike T&gt;
      |          ^
&lt;<span class="k">source</span>&gt;:7:6: note: because <span class="s">'t.init()'</span> would be invalid: no member named <span class="s">'init'</span> <span class="k">in</span> <span class="s">'DigitalInputMock_Bad'</span>
    7 |         { t.init() } -&gt; std::same_as&lt;void&gt;;
      |             ^
1 error generated.
Compiler returned: 1
</code></pre>

<p>If the buttonWithBadMock is commented out, it will churn out this</p>

<pre class="highlight"><code>Real Digital Input, will proceed successfully
Good Mock, will proceed successfully
Bad Mock, will fail to compile <span class="k">if</span> run
</code></pre>
]]>
    </content>
  </entry>
  <entry>
    <title>30 Useful C++ Libraries</title>
    <link rel="alternate" type="text/html" href="https://royyandzakiy.com/blog/2025-12/30-cpp-libraries/"/>
    <id>urn:uuid:957766fd-3067-5130-a1a1-f4d9f6638ab8</id>
    <updated>2025-12-13T00:00:00Z</updated>
    <category term="cpp"/>
    <content type="html">
      <![CDATA[<p>One thing I love doing in my spare time is looking and trying out new C++ Libraries, just checking out what they do, looking into the Hello World examples, compiling it in my pc, store it in my mind inside the “maybe one day I might need this” mental-box 😄</p>

<p>This is a cool list made by Erarnitox</p>

<div class="video-container">
  <iframe src="https://www.youtube.com/embed/J2vGPrVeXig" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="">
  </iframe>
</div>
]]>
    </content>
  </entry>
  <entry>
    <title>C++20 Modules</title>
    <link rel="alternate" type="text/html" href="https://royyandzakiy.com/blog/2025-12/cpp20-modules/"/>
    <id>urn:uuid:14c7b5ec-415e-57d0-a33d-b7af39befeb2</id>
    <updated>2025-12-10T00:00:00Z</updated>
    <category term="cpp"/>
    <content type="html">
      <![CDATA[<p>I’ve been exploring the “new” features of cpp. here I implemented Modules, a feature in cpp20 that by far can only seamlessly be used in the msvc (Visual Studio 17 2022) compiler if using windows</p>

<p>Github Project: <a href="https://github.com/royyandzakiy/cpp-modules-example">github.com/royyandzakiy/cpp-modules-example</a></p>

<p>There are no more header explosion, seperation of includes and src folders, the dreadful circular header includes, or the need to declare functions; which I find very compelling.</p>

<p>Modules still very much allows to use the traditional #include &lt;header&gt;, as long as it gets placed correctly.</p>

<p>I plan to slowly refactor one of my Native Windows Dekstop app to adopt Modules</p>

<p>Here is a good video from CppCon 2023 to learn the basics of it:</p>

<p><a href="https://www.youtube.com/watch?v=_x9K9_q2ZXE">C++ Modules: Getting Started Today - Andreas Weis - CppCon 2023</a></p>

<div class="video-container">
  <iframe src="https://www.youtube.com/embed/_x9K9_q2ZXE" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="">
  </iframe>
</div>

<p>Note: per today, I have tried the latest gcc and clang compilers (in windows) and they do not yet support Modules out of the box (need to either prepare the std module, or add compilation options). cmiiw</p>
]]>
    </content>
  </entry>
  <entry>
    <title>C++ Type Traits &amp; SFINAE</title>
    <link rel="alternate" type="text/html" href="https://royyandzakiy.com/blog/2025-12/typetrait-sfinae/"/>
    <id>urn:uuid:a3a52663-3125-5e06-b27b-8d97ca1b8e52</id>
    <updated>2025-12-07T00:00:00Z</updated>
    <category term="cpp"/>
    <content type="html">
      <![CDATA[<p>One of the tasks I need to do when developing Native Windows App Libraries is creating unit tests for each component. That process requires me to heavily use and maintain Interfaces, or abstract classes, in order to Mock the component in test, and therefore I can force insert specific values. That causes such a headache because of the class inheritence explosion <em>vomit</em></p>

<p>A different approach I find interesting is rather than ‘inheriting’ member variables, it can be done by injecting those variables during initialization (composition). Templates then help me create mocks of some annoying Windows Runtime specific objects like BluetoothAdvertisementWatcher.</p>

<p>Here is some snippets of using Type Traits to enable SFINAE (Substitution Failure is Not an Error), making this kind of Mocking possible.</p>

<p>In this example, I made a digital_input that will be inserted inside a Button class (a study case of Embedded Systems). Here I assume the digital_input is some sort of given library that I need to replace with a Mock. So I created a type trait that gets satisfied iff any type has the init() and read() function in them. I also made an example of a BAD digital_input_mock that does not have the required functions, hence spitting out a compilation error (noice!)</p>

<pre class="highlight"><code><span class="c">// ----------- Type Traits ----------- </span>
<span class="c">// This is the default fallback of the return Type Trait if after any other template </span>
<span class="c">// specialization fails</span>
<span class="k">template</span>&lt;<span class="k">typename</span> <span class="t">T</span>, <span class="k">typename</span> = <span class="t">void</span>&gt;
<span class="k">struct</span> <span class="t">is_digital_input_like</span> : std::false_type {};

<span class="c">// Here, declval acts as a silent instance of T, decltype ensures init() and read() exists, </span>
<span class="c">// resulting into an std::true_type as the final return of template type trait</span>
<span class="k">template</span>&lt;<span class="k">typename</span> <span class="t">T</span>&gt;
<span class="k">struct</span> <span class="t">is_digital_input_like</span>&lt;<span class="t">T</span>, std::<span class="t">void_t</span>&lt;
    <span class="k">decltype</span>(std::declval&lt;<span class="t">T</span>&gt;().init()),
    <span class="k">decltype</span>(std::declval&lt;<span class="t">T</span>&gt;().read())&gt;&gt; : std::true_type {};

<span class="c">// This is a helper to extract the value of the then either std::true_type or false_type</span>
<span class="c">// into the primitive boolean value of `true` or `false`</span>
<span class="k">template</span>&lt;<span class="k">typename</span> <span class="t">T</span>&gt;
<span class="k">constexpr</span> <span class="t">bool</span> is_digital_input_like_v = 
	<span class="t">is_digital_input_like</span>&lt;<span class="t">T</span>&gt;::value;

<span class="c">// ----------- Button Template Class ----------- </span>
<span class="k">template</span> &lt;<span class="k">typename</span> <span class="t">T</span>, <span class="k">typename</span> = std::<span class="t">enable_if_t</span>&lt;is_digital_input_like_v&lt;<span class="t">T</span>&gt;&gt;&gt;
<span class="k">class</span> <span class="t">Button</span> {
<span class="k">public</span>:
	MyButton(<span class="t">T</span> *input) : m_DigitalInput(input) {}

	<span class="t">void</span> init() {
		m_DigitalInput-&gt;init();
		<span class="c">// rest of logic...</span>
	}

	<span class="t">int</span> read() {
		<span class="k">return</span> m_DigitalInput-&gt;read();
	}

<span class="k">private</span>:	
	<span class="t">T</span> *m_DigitalInput;
};

<span class="c">// ----------- Digital Input Classes ----------- </span>
<span class="c">// Digital Input (Real)</span>
<span class="k">class</span> <span class="t">DigitalInput</span> {
<span class="k">public</span>:
	<span class="t">void</span> init() {}
	<span class="t">bool</span> read() { <span class="k">return</span> value_; }

	<span class="t">void</span> set_value(<span class="t">bool</span> v) { value_ = v; }
<span class="k">private</span>:
	<span class="t">bool</span> value_{};
};

<span class="c">// Digital Input (Mock)</span>
<span class="k">class</span> <span class="t">DigitalInputMock</span> {
<span class="k">public</span>:
	<span class="t">void</span> init();
	<span class="t">bool</span> read();
};

<span class="k">auto</span> main() -&gt; <span class="t">int</span> {
    <span class="t">DigitalInputMock</span> digitalInput;
    <span class="t">Button</span>&lt;<span class="t">DigitalInputMock</span>&gt; buttonWithMock(&amp;digitalInput);

	digitalInput.set_value(<span class="k">true</span>);
	std::println(<span class="s">"Test Good Mock"</span>);
	std::println(<span class="s">"button value: {}"</span>, button.read() ? <span class="s">"True"</span> : <span class="s">"False"</span>);
	assert(button.read() == <span class="k">true</span>);

	<span class="k">return</span> <span class="m">0</span>;
}
</code></pre>

<p>Output:</p>

<pre class="highlight"><code>Test Good Mock
button value: True
<span class="c"># assert passess succesfully</span>
</code></pre>

<pre class="highlight"><code><span class="c">// ...</span>

<span class="c">// Digital Input (Bad Mock)</span>
<span class="k">class</span> <span class="t">DigitalInputMock_Bad</span> { 
<span class="k">public</span>:
	<span class="c">/* void init();  */</span> <span class="c">// init() missing!</span>
	<span class="t">bool</span> not_read(); 	<span class="c">// read() missing!</span>
};

<span class="k">auto</span> main() -&gt; <span class="t">int</span> {
    <span class="t">DigitalInputMock_Bad</span> digitalInputBad;
	std::println(<span class="s">"Testing Bad Mock"</span>);
    <span class="t">Button</span>&lt;<span class="t">DigitalInputMock_Bad</span>&gt; buttonWithBadMock(&amp;digitalInputBad); 
	<span class="c">// SFINAE in action! Resulting in a Compile error caused by the Type Trait returning std::false_type</span>

	<span class="k">return</span> <span class="m">0</span>;
}
</code></pre>

<p>Output:</p>

<pre class="highlight"><code>main.cpp(281,5): error C2976: <span class="s">'Button'</span>: too few template arguments, see declaration of <span class="s">'Button'</span>
</code></pre>
]]>
    </content>
  </entry>
  <entry>
    <title>Core-App Architecture for C++ Projects</title>
    <link rel="alternate" type="text/html" href="https://royyandzakiy.com/blog/2025-11/core-app-architecture-cpp/"/>
    <id>urn:uuid:79316ba6-6a73-59b9-8c39-31a67eb1f131</id>
    <updated>2025-11-22T00:00:00Z</updated>
    <category term="cpp"/>
    <content type="html">
      <![CDATA[<p>I’ve been exploring different kinds of C++ project setups. What philosophy do they have, what overarching architecture do they use, what build system do they utilize.</p>

<p>Here, Cherno shares his take on it. He uses Premake (not CMake), and seperates a general Core and App architecture, to later be extendable to more Core components.</p>

<p><a href="https://www.youtube.com/watch?si=muy11EgPpNnuoI3s&amp;v=&amp;feature=youtu.be">The Cherno - How to Properly Setup C++ Projects</a></p>

<div class="video-container">
  <iframe src="https://www.youtube.com/embed/5glH8dGoeCA" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="">
  </iframe>
</div>

<p>Here’s another take, the Open Age of Empire (one of my favorite games as a kid), it also has some great docs.</p>

<p><a href="https://github.com/SFTtech/openage">github.com/SFTtech/openage</a></p>

<p>I’m keen to learning more professional and scalable C++ project setups.</p>
]]>
    </content>
  </entry>
  <entry>
    <title>Extending spdlog into a Custom Logger</title>
    <link rel="alternate" type="text/html" href="https://royyandzakiy.com/blog/2025-11/spdlog-custom-logger/"/>
    <id>urn:uuid:9a5b808b-69e4-5eaf-bf4b-d612a7391771</id>
    <updated>2025-11-10T00:00:00Z</updated>
    <category term="cpp"/>
    <content type="html">
      <![CDATA[<p>Here’s a small attempt to make my C++ projects have better logs. Rather than just using cout or printf, I use the spdlog library, then wrap it with a specific macro convention such as LOG_INFO, LOG_ERR etc. I also add a module based “TAG” and log level control to esily discern who sent what, added log sink to enable option of silent logging to not clutter the console. The reason for this LOG_ style is because my colleagues are used to using this call in their zephyr development, just trying to keep things familiar.</p>

<p><a href="https://github.com/royyandzakiy/cmake-spdlog-logger">github.com/royyandzakiy/cmake-spdlog-logger</a></p>
]]>
    </content>
  </entry>
  <entry>
    <title>Clean CMake for Libraries</title>
    <link rel="alternate" type="text/html" href="https://royyandzakiy.com/blog/2025-10/clean-cmake/"/>
    <id>urn:uuid:df329b30-fd2f-55c7-80cb-d56015e4d637</id>
    <updated>2025-10-17T00:00:00Z</updated>
    <category term="cpp"/>
    <content type="html">
      <![CDATA[<p>I do quite a bit of windows desktop app development, mainly creating libraries for clients to use. I like the notion of the speaker stating that application development and library development can lead to different habits. Using CMake cleanly and with proper SW principles is super essential especially when developing libraries (moreover for OSS). A library dev (and others too) shouldn’t see CMake as just another  helper script to compile, but an integral part of the whole system that we r creating. I think giving a good day to the lib user really shouldn’t be seen as an afterthought. I personally love using CMakePresets, seamless swtiching between IDEs, CI and builds just feels noice 🙂‍↕️</p>

<p><a href="https://www.youtube.com/watch?v=k76LN8dSxx4&amp;feature=youtu.be">Clean CMake for C++ (library) developers - Kerstin Keller - Meeting C++ 2024</a></p>

<div class="video-container">
  <iframe src="https://www.youtube.com/embed/k76LN8dSxx4" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="">
  </iframe>
</div>
]]>
    </content>
  </entry>

</feed>
