gpt4 book ai didi

c++ - 在没有临时变量的情况下直接将cin捕获到函数作为参数

转载 作者:搜寻专家 更新时间:2023-10-31 00:00:30 24 4
gpt4 key购买 nike

更多的是好奇心问题,但实际上有可能通过任何事情吗通过 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));

您可以按任意顺序获取两个整数。

关于c++ - 在没有临时变量的情况下直接将cin捕获到函数作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13028702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com