直接捕获CIN作为参数,而无需临时变量

Directly capturing cin to a function as parameter without a temporary variable

本文关键字:变量 参数 CIN      更新时间:2023-10-16

比其他任何好奇问题要多,但是实际上有可能通过通过 std::cin到一个函数作为参数,没有定义仅用于从输入阅读的临时变量?

而不是使用额外的临时变量:

#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);

我想在功能参数中直接使用std::cin

#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>);

这是可能的吗?

您可以轻松地定义包装函数来执行此操作。

template<class T>
T get(std::istream& is){
  T result;
  is >> result;
  return result;
}

任何体面的编译器都将使用NRVO消除副本。

您可以像这样使用

f(get<int>(std::cin));

不过,请确保在一个语句中不要多次使用它。如果您执行这样的操作,则未指定流操作的顺序。

f(get<int>(std::cin),get<int>(std::cin));

您可以按任一顺序获得两个int。

cin只是一个流,它没有任何魔术。您可以使用其他流方式来执行您想做的任何事情。

查看http://www.cplusplus.com/reference/iostream/

您问题的答案是负面的。为了通过流来输入某些内容,您必须"浪费"变量。如果没有中间变量,您无法将输入数据直接传递给函数。

确定:

f(*std::istream_iterator<T>(std::cin));

,可能不是比使用变量更简单,如果流不提供T