c++ - 这种回调的使用是惯用的吗?

标签 c++ callback idioms

我注意到我的一些代码中有一个共同的模式

std::string line;
if (!in || !std::getline(in, line)) {
  throw line_read_error(in,line_counter);
}
++line_counter;
std::istringstream sin{line};

// ...read from sin...

if (!sin.eof()) {
  sin.clear();
  throw incomplete_read_error(in,line_counter,sin.tellg());j
}

我从线路上读取的内容在每个位置都不同,但设置和读取后检查是相同的。

我把它分解出来,创建一个对象来保存我的 in 流和 line_counter,并传递一个回调 对于 body :

class LineReader {
  std::istream& in;
  size_t line_counter;
public:
  template <typename Function>
  void with_next_line(Function callback) {
    std::string line;
    if (!in || !std::getline(in, line)) {
      throw line_read_error(in,line_counter);
    }
    ++line_counter;
    std::istringstream sin{line};

    callback(sin);

    if (!sin.eof()) {
      sin.clear();
      throw incomplete_read_error(in,line_counter,sin.tellg());j
    }
  }
  // ...
}

改变我的用途

line_reader.with_next_line([/*...*/](auto& sin){
  // ...read from sin...
});

这样重复肯定少了,但是还是有点别扭。

然而,我真正关心的是其他人是否容易 人们要关注,因为我真的在努力使我的代码尽可能清晰。

像这样的东西我会过得更好吗

auto sin = line_reader.get_next_line();

// ...read from sin...

line_reader.check_done(std::move(sin));

最佳答案

执行设置 + 清理的正常方法是拥有一个对象,其构造函数执行设置而析构函数执行清理 (RAII)。

但是,如果您还没有读到最后,您要做的清理工作就是抛出 - 从析构函数中抛出是邪​​恶的、糟糕的和错误的。这意味着您不能在这种特殊情况下使用 RAII。

如果进行检查真的很重要,那么您拥有的代码将执行它。如果它只是“一个好主意”,那么我认为这两个调用(之前和之后)可能比 lambda 稍微干净一些。 (我不会理会 std::move(sin) - 使用 move 在这里并没有真正添加任何东西。)

关于c++ - 这种回调的使用是惯用的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50513391/

相关文章:

javascript - Node.js - 尝试在回调函数中嵌入回调函数

if-statement - 在 Clojure 函数中编写多个 if 检查的更好方法?

c++ - QT signal and slots inside second 类

c++ - 导入错误 : No module named NetCDF

c++ - 无法取消引用指针

android - React-Native Linking.addEventListener ('url' , this._handleOpenURL);不在听

node.js - 为什么我的 Express 应用程序返回空数组?

c++ - 显示列表、OpenGL、C++ 中的 "R6025 - pure virtual call"

javascript - 处理在多个 for 循环中声明的变量的最惯用方法是什么?

Ruby:如何通过对象引用调用函数?