Skip to content

Latest commit

 

History

History
85 lines (64 loc) · 2 KB

310.md

File metadata and controls

85 lines (64 loc) · 2 KB
Info

Example

constexpr auto foo() {
  static constexpr auto value = 42; // error in C++20, okay in C++23
  return value;
}

https://godbolt.org/z/6zK6vj91z

Puzzle

Can you implement to_string_view which converts in-place given characters to string_view?

template<char... Cs>
[[nodiscard]] constexpr auto to_string_view(); // TODO

static_assert(std::string_view{""} == to_string_view<>());
static_assert(std::string_view{"42"} == to_string_view<'4', '2'>());
static_assert(std::string_view{"foo"} == to_string_view<'f', 'o', 'o'>());
static_assert(std::string_view{"bar"} == to_string_view<'b', 'a', 'r'>());

https://godbolt.org/z/4fbYGGxco

Solutions

template<char... Cs>
[[nodiscard]] constexpr auto to_string_view(){
    static constexpr char p[sizeof...(Cs)] = {Cs...};
    return std::string_view(p, sizeof...(Cs));
}

https://godbolt.org/z/r31M7hhno

template<char... Cs>

[[nodiscard]] constexpr auto to_string_view(){
    static constexpr std::array<char, sizeof...(Cs)> chars{Cs...};
    return std::string_view{chars};
}

template<>
[[nodiscard]] constexpr auto to_string_view<>(){
    return std::string_view{};
}

https://godbolt.org/z/eTWasjTTr

[[nodiscard]] constexpr auto to_string_view()
{
    constexpr static std::size_t N = sizeof...(Cs);
    if constexpr (N >0)
    {
        constexpr static std::array<char,N> chars{Cs...};
        return std::string_view(chars.data(),N);
    } else
        return std::string_view("");
}

https://godbolt.org/z/9MMKv98dE

template<char... Cs>
[[nodiscard]] constexpr auto to_string_view() {
  static constexpr char cs[]{Cs..., 0};
  return std::string_view{cs};
}

https://godbolt.org/z/PPdxETv76