std::transform
, as of C++20, is declared constexpr.
I have a bunch of string utility functions that take std::string
arguments, but a lot of the usage ends up just passing in small, short, character literal sequences at compile-time. I thought I would leverage this fact and declare versions that are constexpr
and take std::string_view
s instead of creating temporary std::string
variables just to throw them away...
ORIGINAL STD::STRING
VERSION:
[[nodiscard]] std::string ToUpperCase(std::string string) noexcept {
std::transform(string.begin(), string.end(), string.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c, std::locale("")); });
return string;
}
NEW STD::STRING_VIEW
VERSION:
[[nodiscard]] constexpr std::string_view ToUpperCase(std::string_view stringview) noexcept {
std::transform(stringview.begin(), stringview.end(), stringview.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c, std::locale("")); });
return stringview;
}
But MSVC complains:
error C3892: '_UDest': you cannot assign to a variable that is const
Is there a way to call std::transform
with a std::string_view
and put it back into the std::string_view
or am I going to have to create a local string and return that, thereby defeating the purpose of using std::string_view
in the first place?
[[nodiscard]] constexpr std::string ToUpperCase(std::string_view stringview) noexcept {
std::string copy{stringview};
std::transform(stringview.begin(), stringview.end(), copy.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c, std::locale("")); });
return copy;
}
string_view
is an immutable view into a sequence of characters. It looks but doesn't touch. That's the whole reason it doesn't need to copy anything to form a view of aconst char[]
C-style string literal. – Waddellstring_view
only gives const access - and it is good. How would you want to avoid copying inauto upper = ToUpperCase("foo");
? – Solutionstd::string_view
refers to a constant contiguous sequence. Why not trystd::span<char>
? – Xenogenesisstring_view
(which is non-owning) is already a dangling reference bug, nevermind what the guts of the function do. – Printmaking