In general, the code of the code when there will be a continuous function calls, and each time the result of the call to make a judgment. The following examples:
We define the function func_impl()
, the internal function call func_internal_1(),func_internal_2(),func_internal_3()
. The three function succeeds the return value are both 0, failure has a different error codes.
So as a general way of writing can be written as follows:
void func_impl()
{
int ret;
ret = func_internal_1();
if (ret)
{
std::cout<< "some error"<<std::endl;
return ret;
}
ret = func_internal_2();
if (ret)
{
std::cout<< "some error"<<std::endl;
return ret;
}
ret = func_internal_3();
if (ret)
{
std::cout<< "some error"<<std::endl;
return ret;
}
return 0;
}
As above, no functional problem, but the return value intermediate winded. A large segment of the repeat function independent code! ! !
Reflection: If we can misjudgment Lite, the amount of code will drop a lot!
After some thought, take the following forms:
void func_impl()
{
int ret;
ret = func_internal_1() ||
func_internal_2() ||
func_internal_3();
if (ret)
std::cout<< "some error"<<std::endl;
return ret;
}
As many code amount does decrease, and the use ||
of properties, func_internal_1, func_internal_2, func_internal_3, any one failed, will be directly returned. Indeed in line with expectations, but the downside is that the value will only be ret bool type, only two values, 0 and 1. So in the end we only know the function succeeds or not, without more detailed log, you can not judge func_internal_1, func_internal_2, func_internal_3, which function in the end failed! ! !
Reflection again, into the following form:
// define anyone template function
template <typename T>
auto anyone(T arg) -> decltype(arg)
{
return arg;
}
template <typename T, typename... Args>
auto anyone(T arg, Args... args) -> decltype(arg)
{
return arg ? arg : anyone(args...);
}
void func_impl()
{
int ret;
ret = anyone(func_internal_1(),
func_internal_2(),
func_internal_3());
if (ret)
std::cout<< "some error"<<std::endl;
return ret;
}
ok! pushed to this point using the template feature, we can achieve, ret value is equal to the ultimate failure of the return value of the function, if a reasonable return value is defined, then quickly know where the function fails, the error code and failure !