3 ms·
The C++11 example is the weakest in the article by its own thesis. Public throwing constructor, no year check, no leap-year check, so Birthdate(0, 2, 30) constr
by _alphageek 5mo ago
The C++11 example is the weakest in the article by its own thesis. Public throwing constructor, no year check, no leap-year check, so Birthdate(0, 2, 30) constructs cleanly. The C++17/23 shape (private ctor + static factory) is the actual mechanical insight from King's essay. Make the constructor a function that can fail, so the type itself carries the proof.
- noitpmeder 5mo agoexactly, use std::expected as the return type, avoid exceptions, and make a failable factory constructor to build your type. Make invalid states unrepresentable!!!
- dietr1ch 5mo agoAren't you time-travelling? std::expected is C++23 (so available starting from 2025-2027 xd) https://en.cppreference.com/cpp/utility/expected https://en.cppreference.com/cpp/utility/expected
- diath 5mo agoIt has been available since GCC 12.1 (May 2022), Clang 19.1 (Sep 2024), and Visual Studio 17.13 (2022~): https://godbolt.org/z/on1v6qdf3 https://godbolt.org/z/on1v6qdf3 These days compiler developers implement accepted standard features pretty fast.
- noitpmeder 5mo agoAnd tl::expected (a largely identical impl) has been available similarly as long!
- simonask 5mo agoJust to note, a throwing constructor is “just as good” as static factory method, provided you want to use exceptions for validation errors. Which you shouldn’t, but from the perspective of testing types as proof, it’s just as good.