Common std::cin usage
int X;
cin >> X;
The main disadvantage of this is that X cannot be const. It can easily introduce bugs; and I am looking for some trick to be able to create a const value, and write to it just once.
The naive solution
// Naive
int X_temp;
cin >> X_temp;
const int X = X_temp;
You could obviously improve it by changing X to const&; still, the original variable can be modified.
I’m looking for a short and clever solution of how to do this. I am sure I am not the only one who will benefit from a good answer to this question.
// EDIT: I’d like the solution to be easily extensible to the other types (let’s say, all PODs, std::string and movable-copyable classes with trivial constructor) (if it doesn’t make sense, please let me know in comments).
I’d probably opt for returning an
optional, since the streaming could fail. To test if it did (in case you want to assign another value), useget_value_or(default), as shown in the example.Live example.
To further ensure that the user gets no wall-of-overloads presented when
Tis not input-streamable, you can write a trait class that checks ifstream >> T_lvalueis valid andstatic_assertif it’s not:Live example.
I’m using a
detail::do_streamfunction, since otherwises >> xwould still be parsed insideget_streamand you’d still get the wall-of-overloads that we wanted to avoid when thestatic_assertfires. Delegating this operation to a different function makes this work.