Inside the companion
Modern C++ errors
Follow one pixel through validation, std::expected, and a complete-or-unchanged update.
Project files 6
Keep the last good pixel
Demonstrate an accepted update followed by a rejected update that preserves it.
#include "pixel/pixel.hpp"
#include <exception>
#include <iostream>
namespace {
void print(pixel::Pixel value) {
std::cout << static_cast<int>(value.red) << ' '
<< static_cast<int>(value.green) << ' '
<< static_cast<int>(value.blue) << '\n';
}
}
int main() {
try {
pixel::Pixel current{12, 34, 56};
const auto accepted = pixel::replace_pixel(current, {0.0, 0.25, 1.0});
if (!accepted) {
std::cerr << "Unexpected failure: " << pixel::describe(accepted.error().reason) << '\n';
return 1;
}
std::cout << "accepted: ";
print(current);
const auto rejected = pixel::replace_pixel(current, {0.0, 1.5, 1.0});
if (rejected) {
std::cerr << "Invalid candidate was accepted\n";
return 1;
}
std::cout << "rejected channel " << rejected.error().channel << ": "
<< pixel::describe(rejected.error().reason) << '\n';
std::cout << "still: ";
print(current);
std::cout.flush();
return std::cout ? 0 : 1;
} catch (const std::exception& error) {
std::cerr << "Application failure: " << error.what() << '\n';
return 1;
}
}
This is the file included with the course. Copy and download give you its complete source.
Taking your work offline? Download all course companions
