Standard Library — std::variant, std::visit, and return type deduction C++17 introduced std::variant , a type-safe alternative to unions, alongside std::visit , which allows operations to be performed on the currently active alternative. C++20 extended std::visit with an overload accepting an explicit return type. Consider the following code: #include <variant> #include <type_traits> using Property = std::variant<int, float, bool>; auto visitor = [](auto value) { using T = decltype(value); if constexpr (std::is_same_v<T, int>) return value * 2; else if constexpr (std::is_same_v<T, float>) return value * 0.5f; else return value ? 1 : 0; }; int main() { Property property = 42; // Case A auto a = std::visit(visitor, property); // Case B auto b = std::visit<float>(visitor, property); property = 3.5f; // Case C auto c = std::visit<float>(visitor,...
Let's start by compiling and running this code. For instance: https://godbolt.org/ Code compiles and output is: Case A: 3 Case B: 1 Case C: 150589 The result of Case C is not guaranteed, as we will discuss later. According to the documentation std::mdspan is non-owning multi-dimensional array view that maps a multi-dimensional index to an element of the underlying storage. Since std::mdspan is non-owning, one needs to be careful with lifetime of the data that is accessed via std::mdspan . operator[] doesn't perform bounds checking of the array, leaving all responsibility to the programmer. C++26 introduces a new member function, at() , which performs bounds check but not everyone has the luxury to jump to the latest C++ version. std::mdspan is only a view representing the data so it doesn't change or rearrange data itself. Interface provides some flexibity in configuring layout for the data. Most basic would be std::layout_left an...