直接捕获CIN作为参数,而无需临时变量
Directly capturing cin to a function as parameter without a temporary variable
比其他任何好奇问题要多,但是实际上有可能通过通过 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
。
相关文章:
- 如何将C++闭包与变量参数同时重用——类似于JavaScript
- 带有整数的变量参数列表
- 转发变量参数列表以模拟 std::thread
- 存储稍后要转发的变量参数
- 包括一个类来定义全局变量参数 c++ :(
- 可变参数模板类的构造函数无法接受变量参数
- 变量参数列表 后面的'const std::string&'弄乱了堆栈
- 变量参数崩溃的 C 函数
- 如何使用变量参数化类型?C++
- 使用参数包分配具有变量参数的函数指针
- 参考变量参数与本地参考变量
- 如何以相同的方法在子类中超载的相同方法来实现工作变量参数方法
- 如何基于模板变量参数多次扩展语句
- gmock一种接受变量参数的方法
- 使用变量参数列表与向量(C )的原因
- lambda 中的变量参数作为函数指针
- C 变量参数错误
- 带有变量参数列表的c++11 lambda函数
- 变量参数
- std::函数带有C变量参数,而不是模板变量参数