>>106920831
>>106920989
It's not great but here's an example:
#include <optional>
#include <iostream>
class IncreasingRange {
struct CtorTag { explicit CtorTag() {} };
IncreasingRange(int min, int max) : min{min}, max{max} {}
public:
static std::optional<IncreasingRange> make(const int min, const int max) {
if (min < max) {
return std::optional<IncreasingRange>(std::in_place, CtorTag{}, min, max);
}
return std::nullopt;
}
IncreasingRange(CtorTag, int min, int max) : min{min}, max{max} {}
const int min, max;
~IncreasingRange() { std::cout << "~IncreasingRange()\n"; }
};
std::ostream& operator<<(std::ostream& os, const IncreasingRange& increasingRange) {
os << "IncreasingRange{.min = " << increasingRange.min << ", .max = " << increasingRange.max << "}";
return os;
}
int main() {
int a = 0;
std::cout << "enter a: " << std::flush;
std::cin >> a;
int b = 0;
std::cout << "enter b: " << std::flush;
std::cin >> b;
// IncreasingRange range1{}; // doesn't compile: no constructor
// IncreasingRange range2{a, b}; // doesn't compile: can't call private constructor
// IncreasingRange range3{{}, a, b}; // doesn't compile: can't default-construct the private struct
if (auto increasingRange = IncreasingRange::make(a, b)) {
//increasingRange->min = increasingRange->max + 1; // doesn't compile: can't change value of const members
std::cout << "valid: " << *increasingRange << "\n";
}
else {
std::cerr << "couldn't create IncreasingRange: min = " << a << " to max = " << b << "\n";
}
}
Probably missed something stupid but that's the general idea.