无需布尔变量与提前返回,实现函数步骤流转的现代C++替代方案
现代C++实现步骤链式执行(失败即终止)
当步骤返回值不是bool类型时,你可以用以下几种现代C++的方式简化代码,避免重复的检查逻辑:
方案1:用std::optional绑定状态与结果
如果每个步骤需要返回具体业务结果,失败时无有效输出,std::optional可以把「成功状态」和「结果值」绑定在一起,不用单独维护状态变量。
示例代码:
#include <optional> // 步骤函数返回std::optional<T>:成功返回有效值,失败返回std::nullopt std::optional<int> step_1() { return 1; } std::optional<int> step_2(int input) { return input + 2; } std::optional<int> step_3(int input) { return input * 3; } int my_function() { std::optional<int> result; result = step_1(); if (result) result = step_2(*result); if (result) result = step_3(*result); // 失败时返回默认值,也可根据需求做其他兜底处理 return result.value_or(-1); }
这种写法把状态检查和结果传递合并,比分开维护状态变量和结果变量简洁很多。
方案2:封装链式执行辅助类
如果步骤链比较复杂,可以写一个轻量的执行器类,把步骤串联起来自动处理失败终止逻辑,代码结构会更清晰,后期维护也方便。
示例代码:
#include <utility> template<typename T> class StepExecutor { private: bool success_ = false; T value_; public: // 初始失败状态 StepExecutor() = default; // 初始成功状态,携带初始值 explicit StepExecutor(T val) : success_(true), value_(std::move(val)) {} // 链式添加步骤:只有当前成功才执行传入的函数 template<typename Func> StepExecutor& then(Func&& func) { if (success_) { try { value_ = std::forward<Func>(func)(std::move(value_)); } catch (...) { success_ = false; } } return *this; } // 获取最终结果,失败时返回默认值 T value_or(T default_val) const { return success_ ? value_ : std::move(default_val); } }; // 示例步骤函数 int step_1() { return 1; } int step_2(int x) { return x + 2; } int step_3(int x) { return x * 3; } int my_function() { StepExecutor<int> exec(step_1()) .then(step_2) .then(step_3); return exec.value_or(-1); }
这个类可以按需扩展,比如支持无返回值的步骤、自定义失败回调等,步骤链一目了然。
方案3:C++17折叠表达式+Lambda简化检查
如果是C++17及以上版本,可以用折叠表达式配合Lambda批量处理步骤,代码会非常紧凑。
示例代码(带参数传递的情况):
#include <optional> #include <functional> std::optional<int> step_1() { return 1; } std::optional<int> step_2(int x) { return x + 2; } std::optional<int> step_3(int x) { return x * 3; } int my_function() { std::optional<int> result; // 定义Lambda自动处理步骤执行与状态检查 auto run_step = [&result](auto&& step) { if (result) result = std::forward<decltype(step)>(step)(*result); }; result = step_1(); // 折叠表达式展开所有后续步骤 (run_step(step_2), run_step(step_3)); return result.value_or(-1); }
如果是无参数的bool返回步骤,写法会更简单,直接用折叠表达式批量调用即可。
方案4:异常机制(按需使用)
如果步骤失败属于异常场景(而非预期内的分支),可以用异常终止流程,代码最简洁,但要注意异常的适用场景,不要用在预期内的失败处理上。
示例代码:
#include <stdexcept> // 步骤失败时抛出异常 int step_1() { return 1; } int step_2(int x) { if (x < 0) throw std::runtime_error("step2 failed"); return x + 2; } int step_3(int x) { return x * 3; } int my_function() { int result; try { result = step_1(); result = step_2(result); result = step_3(result); } catch (const std::exception&) { return -1; } return result; }
内容的提问来源于stack exchange,提问作者cam.b
相关产品推荐
相关产品推荐

