Simplifying the use of ref qualifiers in c++20
#include <string>
struct S
{
std::string s_;
std::string_view get() const &
{
return s_;
}
std::string_view get() const && = delete;
};
// I can't change this
struct T
{
T(std::string_view const sv); // does something safe with sv
};
// I can't change this
void f(std::string_view const &);
void g()
{
f(S{}.get()); // should compile
T t(S{}.get()); // should compile
std::string_view sv = S{}.get(); // sh开发者_运维技巧ould not compile
}
Is there way to use ref qualifiers without hindering usability as in the case above? In essence, it should prevent unsafe usage, but allow safe usage. I can wrap f
which does this, but it is unnecessary verbosity
Is there way to use ref qualifiers without hindering usability as in the case above?
No, because when you wrote std::string_view get() const && = delete;
you're essentially(implicitly) saying that S{}.get()
should not be compiled. But then later in the code you're writing f(S{}.get()); // should compile
which contradicts the above code.
Basically, whether or not S{}.get()
can be used is decided by the presence of the std::string_view get() const && = delete;
.
精彩评论