Background:
Lets say I have something like this:
struct item
{
int x;
item(int y): x(y) {}
}
class item_view
{
const item& it;
public:
item_view(const item& it_) : it(it_) {}
friend std::ostream& operator<<(std::ostream& os, const item_view& view)
{return os;} //actually is more complicated
}
The reason why I cannot just overload operator<<
is that it is more human friendly, and view is used to pass the data to SQL, so ticks and some other characters must be escaped.
Problem:
Somebody might want to do something like this:
auto view = item_view(2);
std::cout << view;
This seems to be undefined behavior.
Question:
How can I prevent construction of item_view
from temporaries?
You can provide an additional overload that's a better matches for temporaries and then delete it. For example :
#include <string>
void foo(const std::string &) {}
void foo(std::string &&) = delete;
int main()
{
std::string world = "World";
foo("Hello"); // Doesn't compile, wants to use foo(std::string &&)
foo(world); // Compiles
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With