Directly capturing cin to a function as parameter without a temporary variable
c++, cin
Solution
You can easily define a wrapper function to do this.
template<class T>
T get(std::istream& is){
T result;
is >> result;
return result;
}
Any decent compiler will use NRVO to eliminate the copy.
You can use it like this
f(get<int>(std::cin));
Make sure not to use it multiple times in one statement though. The order of the stream operations is unspecified if you do something like this.
f(get<int>(std::cin),get<int>(std::cin));
You could get the two ints in either order.
Problem
More of a curiosity question than anything else, but is it actually possible to pass whatever goes through `std::cin` to a function as a parameter without defining an temporary variable just for reading from input? Instead of using an extra temporary variable: ``` #include <iostream> using namespace std; string time; // extra define temporary variable for input // now 2 lines follow with separate operations cin >> time; // 1) input to "time" in_time = get_minutes (time); // 2) put "time" to function as parameter cin >> time; // another extra line wake_up = get_minutes (time); cin >> time; // and another other extra line .... opens = get_minutes (time); ``` I want to directly use `std::cin` in a function parameter: ``` #include <iostream> using namespace std; in_time = get_minutes (<use of cin here>); wake_up = get_minutes (<use of cin here>); opens = get_minutes (<use of cin here>); ``` Is this possible?