Skip to content

Latest commit

 

History

History
60 lines (41 loc) · 1.68 KB

346.md

File metadata and controls

60 lines (41 loc) · 1.68 KB
Info

Example

constexpr std::to_chars_result result{{}};
static_assert(result);

https://godbolt.org/z/q16djPn3P

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"});

https://godbolt.org/z/rf7rWc3ee

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);

https://godbolt.org/z/c8vWbGKWf