Hacker News new | ask | show | jobs
by _alphageek 47 days 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.
2 comments

Just 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.
exactly, use std::expected as the return type, avoid exceptions, and make a failable factory constructor to build your type. Make invalid states unrepresentable!!!
Aren't you time-travelling? std::expected is C++23 (so available starting from 2025-2027 xd)

https://en.cppreference.com/cpp/utility/expected

It 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

These days compiler developers implement accepted standard features pretty fast.

And tl::expected (a largely identical impl) has been available similarly as long!