Info
-
Did you know that C++26 added testing for success or failure of functions?
Example
constexpr std::to_chars_result result{{}};
static_assert(result);
Puzzle
- Can you implement
format
fn which optionally converts given value to chars?
template <auto N>
constexpr auto format(const auto value) -> std::optional<std::array<char, N>>; // TODO
constexpr auto fmt_0 = format<1>(0);
static_assert(fmt_0 and std::string_view{fmt_0->cbegin(), fmt_0->cend()} == std::string_view{"0"});
constexpr auto fmt_42 = format<2>(42);
static_assert(fmt_42 and std::string_view{fmt_42->cbegin(), fmt_42->cend()} == std::string_view{"42"});
Solutions
template <auto N>
constexpr auto format(const auto value) -> std::optional<std::array<char, N>> {
std::array<char, N> buffer;
return std::to_chars(buffer.begin(), buffer.end(), value)
? std::optional(buffer)
: std::nullopt;
};
constexpr auto fmt_0 = format<1>(0);
static_assert(fmt_0 and std::string_view{fmt_0->cbegin(), fmt_0->cend()} ==
std::string_view{"0"});
constexpr auto fmt_42 = format<2>(42);
static_assert(fmt_42 and std::string_view{fmt_42->cbegin(), fmt_42->cend()} ==
std::string_view{"42"});
constexpr auto fmt_error = format<1>(42);
static_assert(!fmt_error);