c++ - 减少将参数传递给函数所需的字符串流操作的冗长程度

标签 c++ string stringstream

给定以下代码:

#include <string>
#include <sstream>

int add(int a, int b) {
  return a + b;
}

int main() {
  std::string str = "1 2";
  std::stringstream ss(str);

  int a, b;
  ss >> a;
  ss >> b;
  printf("Result: %d\n", add(a, b));
}

我想知道是否有任何方法可以减少此处部分的冗长:

int a, b;
ss >> a;
ss >> b;
printf("Result: %d\n", add(a, b));

并减少添加到类似内容中的调用:

add(ss >> ?, ss >> ?) // ? because I don't know what'd you'd put there.

基本上,将其变成单行。

最佳答案

据我了解你的问题,你想知道是否有办法减少类似

int a, b;
ss >> a >> b;
cout << (a + b) << endl;

类似于(请注意,这只是伪代码)

cout << ((ss >> ?) + (ss >> ?)) << endl;

没有办法避免声明临时变量。 首先,正如其他人指出的那样,如果操作顺序很重要,则需要它们。其次,您需要在运算符的右侧有一个名称。

您可以手动指定临时对象的名称,但您仍然需要指定它们的类型。 C++ 是一种静态类型语言。 operator>> 无法在右侧为您创建动态推导类型的变量。

出于好奇,我尝试将流中的几个变量的读取抽象为仅类型规范

#include <iostream>
#include <tuple>

template <size_t I=0, typename... T>
std::enable_if_t<I==sizeof...(T)>
collect_impl(std::istream& s, std::tuple<T...>& vars) { }
template <size_t I=0, typename... T>
std::enable_if_t<I!=sizeof...(T)>
collect_impl(std::istream& s, std::tuple<T...>& vars) {
  s >> std::get<I>(vars);
  collect_impl<I+1>(s,vars);
}

template <typename... T>
auto collect(std::istream& s) {
  std::tuple<T...> vars;
  collect_impl(s,vars);
  return vars;
}

void awesome_function(std::tuple<int,int> ii) {
  std::cout << std::get<0>(ii) << ' ' << std::get<1>(ii) << std::endl;
}

void less_awesome_function(int i2, int i1) {
  std::cout << i1 << ' ' << i2 << std::endl;
}

int main() {
  const auto ii = collect<int,int>(std::cin);
  std::cout << std::get<0>(ii) << ' ' << std::get<1>(ii) << std::endl;

  // we can also do
  awesome_function(collect<int,int>(std::cin));

  // with C++17 apply we can even do this
  std::apply(less_awesome_function,collect<int,int>(std::cin));
}

关于c++ - 减少将参数传递给函数所需的字符串流操作的冗长程度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42214101/

相关文章:

c++ - 线弯曲的简单算法

c++ - QT中动态添加QObject的SIGNAL(带参数)如何处理?

javascript - 在正则表达式 Javascript 中获取内部字符串前后的字符串

c - 没有字符串数组的输出

c++ - 关于多线程程序的查询

c++ - 为继承 enable_shared_from_this 的类获取 unique_ptr

php - 在php中将长度超过16位的int转换为字符串

c++ - istream 没有完全恢复已放入 stringstream 的内容

c++ - std::stringstream 从字符串中读取 int 和字符串

c++ - std::cout << stringstream.str()->c_str() 什么都不打印