c++ 一遍又一遍地对函数返回相同的检查
c++ Same checking on function return over and over again
int cmd_x() {
int result;
result = func1(x, y);
if (result != 0) {
return result;
}
result = func2();
if (result != 0) {
return result;
}
result = func1(x, y, z, w);
if (result != 0) {
return result;
}
...
return result;
}
cmd_x
瀑布式上执行多种功能。每个函数返回result
。我应该确保result
是成功的,以便继续下一步。
此if
条件在代码上多次出现,这使得它更难遵循和阅读。
有没有办法干净地摆脱这种情况?
我正在考虑创建一个函数指针数组并循环它以仅检查一次代码,但由于函数参数的数量不同,我无法实现它。
这看起来很像错误处理("如果我得到一个非零错误代码,请停止并返回该代码")。如果这些错误是异常的,那么在func1
等中使用异常处理可能是有意义的 - 如果它们会返回非零错误代码,它们会抛出期望。然后,可以在最合适的位置(可能是多个函数调用)捕获此异常,从而避免在整个调用层次结构中一直执行错误处理。
如果错误不是例外,事情就会变得复杂。如果可以将所有函数调用打包到某种容器中,则可以迭代该容器。这里的问题是找到函数的通用类型。
或者,可变参数模板可以完成这项工作:
template<class Func, class... OtherFuncs>
int cmd_x_impl(Func&& func, OtherFuncs&&... otherFuncs)
{
int result = func();
if (result != 0)
return result;
cmd_x_impl(otherFuncs...);
}
template<class Func>
int cmd_x_impl(Func&& func)
{
return func();
}
int cmd_x() {
return cmd_x_impl(
[&]() { return func1(x, y); },
[&]() { return func2(); },
[&]() { return func1(x, y, z, w); }
);
}
https://godbolt.org/g/wihtCj
这会将所有函数调用包装在 lambda 中,然后使用可变参数模板递归一个接一个地调用它们,只要每个结果为 0。与另一个答案中显示的std::function
方法相比,其优势在于编译器更容易查看和优化。它的使用也更简洁,更可重复使用。
我可以想到以下方法来简化您的代码。
选项 1:使用条件表达式
int cmd_x()
{
int x = 0, y = 0, z = 0, w = 0;
int result = func1(x, y);
result = (result != 0) ? result : func2();
result = (result != 0) ? result : func1(x, y, z, w);
// ...
result = (result != 0) ? result : funcN();
return result;
}
选项 2:使用std::function
秒的std::vector
int cmd_x()
{
int x = 0, y = 0, z = 0, w = 0;
std::vector<std::function<int()>> functionList =
{
// Let the lambda functions capture what they need
[x, y]() -> int { return func1(x, y); },
[] () -> int { return func2(); },
[x, y, z, w] () -> int { return func1(x, y, z, w); },
[] () -> int { return funcN(); }
};
for ( auto fn : functionList )
{
int result = fn();
if ( result != 0 )
{
return result;
}
}
return 0;
}
选项 3:使用帮助程序函数并std::function
这是一种混合方法,在帮助程序函数中使用条件表达式,在主函数中使用 lambda 函数。
int cmd_helper(int r, std::function<int()> fn)
{
return ( r != 0 ) ? r : fn();
}
int cmd_x()
{
int x = 0, y = 0, z = 0, w = 0;
int result = 0;
result = cmd_helper(result, [x, y]() -> int { return func1(x, y); });
result = cmd_helper(result, [] () -> int { return func2(); });
result = cmd_helper(result, [x, y, z, w] () -> int { return func1(x, y, z, w); });
result = cmd_helper(result, [] () -> int { return funcN(); });
return result;
}
相关文章:
- 检查由括号、方括号和大括号组成的一组方括号是否有效?
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 在运行时检查继承是否只有一种类型和 void*
- 静态代码检查器抱怨.虚惊一场?
- 编写了一个C++代码来检查表达式是否具有平衡括号并且我的代码未运行.我已经卡了一天了
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 为什么当我输入一个大数字时,输出会一遍又一遍地重复?
- 我可以一次检查一小堆布尔值吗?
- 我如何一遍又一遍地向用户提问,直到他们输入正确的值字段?
- c++ 一遍又一遍地对函数返回相同的检查
- LIBZIP 是否提供了一种检查zip_file是否是目录的方法?
- 一遍又一遍地构造相同的对象
- Boost或标准库是否提供了一种检查演员阵容是否无损的方法
- 有没有办法不在 c++ 中的参数中一遍又一遍地输入相同的数据类型
- 一遍又一遍地创建同一个文本文件
- 另一种检查应用程序是否安装在MAC OS X上的方法
- 变量不计数,即使一遍又一遍地调用函数
- 如何避免一遍又一遍地编写相同的模板
- 一遍又一遍地传递对象的替代方法
- 一遍又一遍地验证文件时遇到问题