Skip to content

Commit

Permalink
Get asprintf to work with string_view in the args list
Browse files Browse the repository at this point in the history
Based on a question over in Zitrax's gist:
(https://gist.github.com/Zitrax/a2e0040d301bf4b8ef8101c0b1e3f1d5), we
use static_cast, combined with std::move and std::forward in
unistd::asprintf_convert to get unistd::asprintf to work with
std::string_view in the argument list.

There are two other variations on the return line that also work, but
I chose std::forward to keep things the same.

I also wonder if this might not introduce a memory leak?
  • Loading branch information
Dyrcona committed Nov 7, 2023
1 parent 1d03252 commit 02cb784
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion include/unistd/asprintf.h
Expand Up @@ -24,7 +24,11 @@ namespace unistd {

template<typename T>
auto asprintf_convert(T&& t) {
if constexpr (std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, std::string>) {
if constexpr (std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, std::string_view>) {
std::string s = std::move(static_cast<std::string>(t));
return std::forward<std::string>(s).c_str();
}
else if constexpr (std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, std::string>) {
return std::forward<T>(t).c_str();
}
else {
Expand Down

0 comments on commit 02cb784

Please sign in to comment.