如何重构该C++代码以避免stack处理逻辑的大量重复?
方案合理性说明
你想把公共逻辑抽成辅助函数的思路完全合理,是消除这类分支重复的标准做法,剩下的比较运算符差异可以用以下几种方案处理:
可行实现方案
方案1:传入比较谓词(C++11及以上推荐)
直接把比较逻辑作为lambda参数传给辅助函数,无额外运行时开销,可读性高:
class { public: void func(const int val, const bool flag) { if(flag) { helper(lower, val, [](int a, int b) { return a <= b; }); } else { helper(higher, val, [](int a, int b) { return a >= b; }); } } template<typename Compare> void helper(std::stack<int> &st, const int val, Compare comp) { while(!st.empty() && comp(val, st.top())) { // 原公共处理逻辑直接复用即可 } } private: std::stack<int> lower; std::stack<int> higher; };
方案2:用std::function做类型擦除(适合隐藏实现的场景)
如果不希望辅助函数是模板、需要放到cpp文件实现,可以用标准库的function封装比较逻辑:
#include <functional> class { public: void func(const int val, const bool flag) { if(flag) { helper(lower, val, std::less_equal<int>()); } else { helper(higher, val, std::greater_equal<int>()); } } void helper(std::stack<int> &st, const int val, std::function<bool(int, int)> comp) { while(!st.empty() && comp(val, st.top())) { // 公共处理逻辑 } } private: std::stack<int> lower; std::stack<int> higher; };
方案3:内部判断flag(最简写法,适合逻辑固定场景)
如果只有这两种比较逻辑、后续不会扩展,可以直接把flag作为参数传入辅助函数,内部判断使用的比较符,代码量最小:
class { public: void func(const int val, const bool flag) { helper(flag ? lower : higher, val, flag); } void helper(std::stack<int> &st, const int val, bool flag) { while(!st.empty() && (flag ? val <= st.top() : val >= st.top())) { // 公共处理逻辑 } } private: std::stack<int> lower; std::stack<int> higher; };
选型建议
- 追求性能、后续可能扩展其他比较逻辑选方案1
- 希望隐藏辅助函数实现、可接受微小运行时开销选方案2
- 逻辑固定、想要最少代码量选方案3
内容的提问来源于stack exchange,提问作者westcoaststudent
相关产品推荐
相关产品推荐

