Inside the companion
Modern C++ errors
Follow one pixel through validation, std::expected, and a complete-or-unchanged update.
Project files 6
Make failure part of the interface
Typed channel errors, pixel results, and the commit interface.
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <string_view>
namespace pixel {
struct Pixel {
std::uint8_t red{};
std::uint8_t green{};
std::uint8_t blue{};
bool operator==(const Pixel&) const = default;
};
enum class ChannelError { non_finite, outside_unit_interval };
struct PixelError {
std::size_t channel;
ChannelError reason;
};
[[nodiscard]] std::string_view describe(ChannelError error) noexcept;
// An intentionally bounded SDR example using a gamma-2 approximation, not sRGB.
[[nodiscard]] std::expected<std::uint8_t, ChannelError> encode_channel(double linear);
[[nodiscard]] std::expected<Pixel, PixelError> prepare_pixel(std::array<double, 3> linear);
// Intentional in-out operation: replace only after all three channels succeed.
[[nodiscard]] std::expected<void, PixelError> replace_pixel(
Pixel& current, std::array<double, 3> linear);
}
This is the file included with the course. Copy and download give you its complete source.
Taking your work offline? Download all course companions
