{"id":11483,"date":"2026-11-29T14:43:46","date_gmt":"2026-11-29T14:43:46","guid":{"rendered":"https:\/\/www.modernescpp.com\/?p=11483"},"modified":"2026-11-29T14:43:46","modified_gmt":"2026-11-29T14:43:46","slug":"most-valuable-std-variant-part-1","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/most-valuable-std-variant-part-1\/","title":{"rendered":"Most Valuable std::variant (Part 1)"},"content":{"rendered":"\r\n<p class=\"wp-block-paragraph\">Most <code>std::variant<\/code> tutorials introduce it as a way to store wildly different types in a single variable \u2013 the canonical example being a JSON-like value type that can hold a number, a bool, a string, or a null.<\/p>\r\n\r\n\r\n<!-- HTML generated using hilite.me -->\r\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\r\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #069; font-weight: bold;\">using<\/span> value_t <span style=\"color: #555;\">=<\/span> std<span style=\"color: #555;\">::<\/span>variant<span style=\"color: #555;\">&lt;<\/span>\r\n    std<span style=\"color: #555;\">::<\/span>monostate,\r\n    <span style=\"color: #078; font-weight: bold;\">int<\/span>,\r\n    <span style=\"color: #078; font-weight: bold;\">double<\/span>,\r\n    <span style=\"color: #078; font-weight: bold;\">bool<\/span>,\r\n    std<span style=\"color: #555;\">::<\/span>string\r\n<span style=\"color: #555;\">&gt;<\/span>;\r\n<\/pre>\r\n<\/div>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">While this is a valid use case, it has always been my pet peeve to see examples like this one in articles introducing <code>std::variant<\/code>. They miss what I consider the most important application of <code>std::variant<\/code> \u2013 improving software safety by eliminating invalid program states.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">In both cases, we create a new type that is a union of some simpler types. In the previous example, the different alternatives (<code>int<\/code>, <code>std::string<\/code>, etc.) are all unrelated values \u2013 the variant just holds whichever one was most recently assigned.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">In state modelling, the alternatives are operational states \u2013 the variant encodes what the program is currently doing and what data is meaningful and useful right now.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Same operation of combining types, but the semantic difference of why we combine the types is what is important.<\/p>\r\n\r\n\r\n\r\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"When_RAII_gets_switched_off\"><\/span>When RAII gets switched off<span class=\"ez-toc-section-end\"><\/span><\/h2>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">RAII \u2013 Resource Acquisition Is Initialization \u2013 is probably the most important idiom of C++. When an object is constructed, the resource is acquired. When it is destroyed, the resource is released. The destructor does the cleanup, and since the destructor is called automatically whenever the object goes out of scope, the cleanup cannot be forgotten.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">We are not going to have classes that need explicitly implemented destructors in this post. But if you do need to do some explicit resource management, <strong>mind your rule of N<\/strong>. The destructor is only a part of the story. A class that manages a resource also needs correct copy and move operations, otherwise the resource can still be leaked or released twice. Rainer explained this in detail in <a href=\"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-constructors-assignments-and-desctructors\/\">C++ Core Guidelines: The Rule of Zero, Five, or Six<\/a>.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Consider a function that writes some results to a file:<\/p>\r\n\r\n\r\n<!-- HTML generated using hilite.me -->\r\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\r\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #078; font-weight: bold;\">void<\/span> <span style=\"color: #c0f;\">write_results<\/span>(<span style=\"color: #069; font-weight: bold;\">const<\/span> std<span style=\"color: #555;\">::<\/span>string<span style=\"color: #555;\">&amp;<\/span> filename,\r\n                   <span style=\"color: #069; font-weight: bold;\">const<\/span> std<span style=\"color: #555;\">::<\/span>string<span style=\"color: #555;\">&amp;<\/span> content)\r\n{\r\n    std<span style=\"color: #555;\">::<\/span>ofstream file{filename};\r\n    file <span style=\"color: #555;\">&lt;&lt;<\/span> content;\r\n\r\n    <span style=\"color: #09f; font-style: italic;\">\/\/ 'file' goes out of scope here.<\/span>\r\n    <span style=\"color: #09f; font-style: italic;\">\/\/ Its destructor flushes the buffer and closes<\/span>\r\n    <span style=\"color: #09f; font-style: italic;\">\/\/ the underlying file handle automatically.<\/span>\r\n    <span style=\"color: #09f; font-style: italic;\">\/\/ There is nothing to forget.<\/span>\r\n}\r\n<\/pre>\r\n<\/div>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">When the <code>write_results<\/code> function returns, <code>file<\/code> goes out of scope, its destructor is called. The destructor flushes the buffer and closes the file handle. There is no need for an explicit <code>file.close()<\/code> call.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">The same principle applies to any resource. Memory managed by <code>std::unique_ptr<\/code> is freed when it goes out of scope. A mutex locked with <code>std::lock_guard<\/code> is unlocked when the guard goes out of scope. A database connection wrapped in a custom RAII type is closed when the wrapper is destroyed. RAII is the reason why manual resource management is largely a solved problem in modern C++.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">But, what happens when such a resource is not a local variable, but a member of a larger class?<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Imagine we are writing a small report-generator application. It has a clear lifecycle:<\/p>\r\n\r\n\r\n\r\n<ol class=\"wp-block-list\">\r\n<li>It starts idle, holding only its output configuration.<\/li>\r\n\r\n\r\n\r\n<li>It transitions to a running state, opens an output file, and processes a series of items, writing each one to the file.<\/li>\r\n\r\n\r\n\r\n<li>Finally it completes, at which point the file should be closed and the application should hold a summary of what was done.<\/li>\r\n<\/ol>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">The usual approach to model something like this is to start with a class that will contain all the data we will need to implement this simple process:<\/p>\r\n\r\n\r\n<!-- HTML generated using hilite.me -->\r\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\r\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #069; font-weight: bold;\">class<\/span> <span style=\"color: #0a8; font-weight: bold;\">application_t<\/span> {\r\n<span style=\"color: #069; font-weight: bold;\">public<\/span><span style=\"color: #555;\">:<\/span>\r\n    <span style=\"color: #069; font-weight: bold;\">explicit<\/span> application_t(std<span style=\"color: #555;\">::<\/span>string output_path)\r\n        <span style=\"color: #555;\">:<\/span> m_output_path{std<span style=\"color: #555;\">::<\/span>move(output_path)}\r\n    {}\r\n\r\n    <span style=\"color: #078; font-weight: bold;\">void<\/span> start()\r\n    {\r\n        <span style=\"color: #09f; font-style: italic;\">\/\/ Let's assume this always succeeds<\/span>\r\n        m_output_file.open(m_output_path);\r\n        m_running <span style=\"color: #555;\">=<\/span> <span style=\"color: #366;\">true<\/span>;\r\n    }\r\n\r\n    <span style=\"color: #078; font-weight: bold;\">void<\/span> process(<span style=\"color: #069; font-weight: bold;\">const<\/span> std<span style=\"color: #555;\">::<\/span>string<span style=\"color: #555;\">&amp;<\/span> item)\r\n    {\r\n        <span style=\"color: #069; font-weight: bold;\">if<\/span> (<span style=\"color: #555;\">!<\/span>m_running) <span style=\"color: #069; font-weight: bold;\">return<\/span>;\r\n        m_output_file <span style=\"color: #555;\">&lt;&lt;<\/span> item <span style=\"color: #555;\">&lt;&lt;<\/span> <span style=\"color: #c30;\">'\\n'<\/span>;\r\n        <span style=\"color: #555;\">++<\/span>m_item_count;\r\n    }\r\n\r\n    <span style=\"color: #078; font-weight: bold;\">void<\/span> stop()\r\n    {\r\n        m_output_file.close(); <span style=\"color: #09f; font-style: italic;\">\/\/ easy to forget<\/span>\r\n        m_running <span style=\"color: #555;\">=<\/span> <span style=\"color: #366;\">false<\/span>;\r\n    }\r\n\r\n    std<span style=\"color: #555;\">::<\/span><span style=\"color: #078; font-weight: bold;\">size_t<\/span> item_count() <span style=\"color: #069; font-weight: bold;\">const<\/span>\r\n    {\r\n        <span style=\"color: #069; font-weight: bold;\">return<\/span> m_item_count;\r\n    }\r\n\r\n<span style=\"color: #069; font-weight: bold;\">private<\/span><span style=\"color: #555;\">:<\/span>\r\n    std<span style=\"color: #555;\">::<\/span>string   m_output_path;\r\n    std<span style=\"color: #555;\">::<\/span>ofstream m_output_file;      <span style=\"color: #09f; font-style: italic;\">\/\/ only meaningful while running<\/span>\r\n    <span style=\"color: #078; font-weight: bold;\">bool<\/span>          m_running{<span style=\"color: #366;\">false<\/span>};\r\n    std<span style=\"color: #555;\">::<\/span><span style=\"color: #078; font-weight: bold;\">size_t<\/span>   m_item_count{<span style=\"color: #f60;\">0UZ<\/span>};  <span style=\"color: #09f; font-style: italic;\">\/\/ no meaning before we start<\/span>\r\n};\r\n<\/pre>\r\n<\/div>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">The class is small, the code compiles, and the tests pass. So, all is perfect! Right?<\/p>\r\n\r\n\r\n\r\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_hidden_coupling_and_the_invalid_state\"><\/span>The hidden coupling and the invalid state<span class=\"ez-toc-section-end\"><\/span><\/h2>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Look more carefully at the member variables:<\/p>\r\n\r\n\r\n<!-- HTML generated using hilite.me -->\r\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\r\n<pre style=\"margin: 0; line-height: 125%;\">std<span style=\"color: #555;\">::<\/span>string   m_output_path;\r\nstd<span style=\"color: #555;\">::<\/span>ofstream m_output_file;      <span style=\"color: #09f; font-style: italic;\">\/\/ only meaningful while running<\/span>\r\n<span style=\"color: #078; font-weight: bold;\">bool<\/span>          m_running{<span style=\"color: #366;\">false<\/span>};\r\nstd<span style=\"color: #555;\">::<\/span><span style=\"color: #078; font-weight: bold;\">size_t<\/span>   m_item_count{<span style=\"color: #f60;\">0UZ<\/span>};  <span style=\"color: #09f; font-style: italic;\">\/\/ no meaning before we start<\/span>\r\n<\/pre>\r\n<\/div>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Each of these four members is present in every instance of <code>application_t<\/code>, during its whole lifetime.<\/p>\r\n\r\n\r\n\r\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Dead_member_variables\"><\/span>Dead member variables<span class=\"ez-toc-section-end\"><\/span><\/h3>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">When the object is first constructed, <code>m_output_file<\/code> is a default-constructed, closed <code>std::ofstream<\/code>. It is unused until <code>start()<\/code> is eventually called. Same with <code>m_item_count<\/code>.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Similarly, <code>m_output_path<\/code> and <code>m_output_file<\/code> are dead weight that will never be used again after <code>stop()<\/code> is called.<\/p>\r\n\r\n\r\n\r\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Implicit_coupling_between_members\"><\/span>Implicit coupling between members<span class=\"ez-toc-section-end\"><\/span><\/h3>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Another issue is the implicit contract between <code>m_running<\/code> and <code>m_output_file<\/code>. For the class to be in a valid state, these two must always agree with each other: if <code>m_running<\/code> is <code>true<\/code>, the file must be open; if <code>m_running<\/code> is <code>false<\/code>, the file should be closed.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Nothing in the type system enforces this contract. Any member function can change <code>m_running<\/code> without touching the file, or open the file without setting <code>m_running<\/code>.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">As the class grows, every new member function is one more place where the contract can be accidentally violated. The more member variables we end up putting in the class, the more coupling we will have. And it will not be obvious which variables are coupled, and which are not.<\/p>\r\n\r\n\r\n\r\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"RAII_fires_too_late\"><\/span>RAII fires too late<span class=\"ez-toc-section-end\"><\/span><\/h3>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">There is also the matter of <code>m_output_file.close()<\/code> in the <code>stop()<\/code> function. Why do we have RAII, if we still need to manually release resources? RAII has been undermined when we connected the lifetime of the resource to the lifetime of the owning instance of the <code>application_t<\/code> class. These two lifetimes should not be the same.<\/p>\r\n\r\n\r\n\r\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"A_class_with_too_many_responsibilities\"><\/span>A class with too many responsibilities<span class=\"ez-toc-section-end\"><\/span><\/h3>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Step back and look at what <code>application_t<\/code> is at each point in its lifetime:<\/p>\r\n\r\n\r\n\r\n<ul class=\"wp-block-list\">\r\n<li>Before <code>start()<\/code>: effectively a configuration struct, carrying only <code>m_output_path<\/code>.<\/li>\r\n\r\n\r\n\r\n<li>Between <code>start()<\/code> and <code>stop()<\/code>: an active file writer, managing an open stream and a running count.<\/li>\r\n\r\n\r\n\r\n<li>After <code>stop()<\/code>: a result summary, holding only <code>m_item_count<\/code>.<\/li>\r\n<\/ul>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">These are three different roles, each with its own data and its own invariants. The single-responsibility principle says that a class should have one reason to change \u2013 but this class has (at least) three. Lumping these three roles into a single class means that every role must carry the dead weight of the other two. The transitions between the roles are maintained only by programmer discipline, not by anything the language can check.<\/p>\r\n\r\n\r\n\r\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Splitting_the_class_into_states\"><\/span>Splitting the class into states<span class=\"ez-toc-section-end\"><\/span><\/h2>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">The fix starts with recognising that <code>application_t<\/code> is not really a single thing. It is three things that happen to share a name. The correct representation is three separate types, one per state, each containing only the data relevant to that state:<\/p>\r\n\r\n\r\n<!-- HTML generated using hilite.me -->\r\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\r\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #069; font-weight: bold;\">struct<\/span> <span style=\"color: #0a8; font-weight: bold;\">idle_t<\/span> {\r\n    std<span style=\"color: #555;\">::<\/span>string output_path;\r\n};\r\n\r\n<span style=\"color: #069; font-weight: bold;\">struct<\/span> <span style=\"color: #0a8; font-weight: bold;\">running_t<\/span> {\r\n    <span style=\"color: #069; font-weight: bold;\">explicit<\/span> running_t(<span style=\"color: #069; font-weight: bold;\">const<\/span> std<span style=\"color: #555;\">::<\/span>string<span style=\"color: #555;\">&amp;<\/span> path)\r\n        <span style=\"color: #555;\">:<\/span> file{path}\r\n    {}\r\n\r\n    std<span style=\"color: #555;\">::<\/span>ofstream file;\r\n    std<span style=\"color: #555;\">::<\/span><span style=\"color: #078; font-weight: bold;\">size_t<\/span> item_count{<span style=\"color: #f60;\">0UZ<\/span>};\r\n};\r\n\r\n<span style=\"color: #069; font-weight: bold;\">struct<\/span> <span style=\"color: #0a8; font-weight: bold;\">done_t<\/span> {\r\n    std<span style=\"color: #555;\">::<\/span><span style=\"color: #078; font-weight: bold;\">size_t<\/span> item_count;\r\n};\r\n<\/pre>\r\n<\/div>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">With those types in hand, <code>application_t<\/code> becomes a simple alias:<\/p>\r\n\r\n\r\n<!-- HTML generated using hilite.me -->\r\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\r\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #069; font-weight: bold;\">using<\/span> application_t <span style=\"color: #555;\">=<\/span> std<span style=\"color: #555;\">::<\/span>variant<span style=\"color: #555;\">&lt;<\/span>\r\n    idle_t,\r\n    running_t,\r\n    done_t\r\n<span style=\"color: #555;\">&gt;<\/span>;\r\n<\/pre>\r\n<\/div>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">An <code>application_t<\/code> object is always in exactly one of the three states. There is no fourth possibility (apart from the <code>valueless_by_exception<\/code>, but this is not a situation we can be in in this case), no combination of flags and half-open files that the program has to guard against.<\/p>\r\n\r\n\r\n\r\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_we_gain\"><\/span>What we gain<span class=\"ez-toc-section-end\"><\/span><\/h2>\r\n\r\n\r\n\r\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Automatic_disposal_when_leaving_a_state\"><\/span>Automatic disposal when leaving a state<span class=\"ez-toc-section-end\"><\/span><\/h3>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Look at the <code>stop()<\/code> function which changes the program state from <code>running_t<\/code> to <code>done_t<\/code>:<\/p>\r\n\r\n\r\n<!-- HTML generated using hilite.me -->\r\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\r\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #078; font-weight: bold;\">void<\/span> <span style=\"color: #c0f;\">stop<\/span>(application_t<span style=\"color: #555;\">&amp;<\/span> app)\r\n{\r\n    <span style=\"color: #069; font-weight: bold;\">if<\/span> (<span style=\"color: #069; font-weight: bold;\">auto<\/span><span style=\"color: #555;\">*<\/span> s <span style=\"color: #555;\">=<\/span> std<span style=\"color: #555;\">::<\/span>get_if<span style=\"color: #555;\">&lt;<\/span>running_t<span style=\"color: #555;\">&gt;<\/span>(<span style=\"color: #555;\">&amp;<\/span>app)) {\r\n        <span style=\"color: #069; font-weight: bold;\">auto<\/span> count <span style=\"color: #555;\">=<\/span> s<span style=\"color: #555;\">-&gt;<\/span>item_count;\r\n        app <span style=\"color: #555;\">=<\/span> done_t{count};\r\n    }\r\n}\r\n<\/pre>\r\n<\/div>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">When we assign <code>done_t{count}<\/code> to <code>app<\/code>, the <code>std::variant<\/code> destroys the value it currently holds \u2013 and replaces it with the new value. Destroying the <code>running_t<\/code> calls the destructor of its <code>std::ofstream<\/code> member, which flushes the buffer and closes the file.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">We did not call <code>file.close()<\/code> explicitly. Closing the file is no longer something we have to do \u2013 it is a consequence of leaving the running state. RAII is restored.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">The same reasoning applies to any resource. Whatever a state holds \u2013 heap memory, a mutex lock, a network socket \u2013 is released automatically when the program transitions away from that state, regardless of how the transition happens.<\/p>\r\n\r\n\r\n\r\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"No_implicit_coupling_between_members\"><\/span>No implicit coupling between members<span class=\"ez-toc-section-end\"><\/span><\/h3>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">In the original <code>application_t<\/code>, <code>m_running<\/code> and <code>m_output_file<\/code> had to be kept in sync by hand. In the variant design, this question does not arise. If the current state is <code>running_t<\/code>, the file is open \u2013 it was opened in the constructor, and it will be closed when that state is left. There is no separate boolean flag to get out of sync with anything. Each state type contains exactly the members it needs, and nothing else.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">These state types can also grow, which can lead to new couplings getting introduced. But separating coupled from uncoupled member variables will still be easier as the state types are still significantly smaller than what they would have been if all are bunched together in a single class.<\/p>\r\n\r\n\r\n\r\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Invariants_are_maintained_by_construction\"><\/span>Invariants are maintained by construction<span class=\"ez-toc-section-end\"><\/span><\/h3>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">With the flat class it was possible to have an instance where <code>m_running<\/code> was <code>true<\/code> but the file was closed, or where the file was open long after processing had stopped. Nothing in the type system prevented it.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">With the variant, these invalid combinations cannot be represented at all. A <code>running_t<\/code> always has an open file (assuming construction succeeded). A <code>done_t<\/code> has no file member, open or otherwise. The type system, rather than programmer discipline, enforces the invariants.<\/p>\r\n\r\n\r\n\r\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_is_coming_in_the_next_parts\"><\/span>What is coming in the next parts<span class=\"ez-toc-section-end\"><\/span><\/h2>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">We have seen how modeling program state using <code>std::variant<\/code> restores RAII, reduces or even eliminates implicit coupling between members, and makes invalid program states impossible to represent.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">The transition functions like <code>stop()<\/code> above use <code>std::get_if<\/code> to inspect the active state and assign a new state directly. This works for small examples, but it does not scale well when many states are involved and transitions need to handle the current state in a generic manner.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">In the next part, we will look at <code>std::visit<\/code> together with the overloaded pattern, which lets us write a single expression that handles every possible state cleanly. We will also see how to write transition functions that can prevent accidentally accessing a state that has already been transitioned away from to make the programs even more safe and robust.<br \/><br \/><br \/><\/p>\r\n","protected":false},"excerpt":{"rendered":"<p>Most tutorials introduce std::variant as a way to store unrelated types in one variable. Ivan \u010cuki\u0107 shows its far more valuable use: modelling program states so that invalid states can&#8217;t be represented, RAII works again, and hidden coupling between members disappears.<\/p>\n","protected":false},"author":32,"featured_media":11484,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[567],"tags":[468,466,440],"class_list":["post-11483","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-safety","tag-raii","tag-safety","tag-variant"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/11483","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/users\/32"}],"replies":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/comments?post=11483"}],"version-history":[{"count":6,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/11483\/revisions"}],"predecessor-version":[{"id":11486,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/11483\/revisions\/11486"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/11484"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=11483"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=11483"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=11483"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}