std convert uint16_t to string_view

31 Views Asked by At

I want to convert std::uint16_t to std::string_view. I was expecting the following code would work:

std::string_view to_str(std::uint16_t v) {
    return std::string_view(std::to_string(v));
}

because it uses an intermediary std::string in to_str function scope. I know I can use a static storage for intermediary string like this:

std::string_view to_str(std::uint16_t v) {
    static auto str = std::to_string(v);
    return std::string_view(str);
}

I know there is another way to use char buffer and convert it to string_view but I wonder is there any better way to serve this very same purpose? Is it even logical to return string_view instead of string?

0

There are 0 best solutions below