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).