避免"local variable as default parameter"的最佳设计?

Best design to avoid "local variable as default parameter"?

本文关键字:最佳 default local variable as 避免 parameter      更新时间:2023-10-16

我正在编写一个近似函数,将两个不同的公差值作为参数:

bool Approximate(vector<PointC*>* pOutput, LineC input, double horizontalTolerance, double verticalTolerance)
如果未设置垂直容差

,我希望函数设置垂直容差 = 水平容差。所以,我想完成这样的事情:

bool Approximate(vector<PointC*>* pOutput, LineC input, double horizontalTolerance, double verticalTolerance=horizontalTolerance)

我知道这是不可能的,因为局部变量不允许作为默认参数。所以我的问题是,设计这个功能的最佳方法是什么?

我想到的选项是:

  1. 不要使用默认参数,并让用户显式设置两个公差。

  2. 将"垂直容差"的默认值设置为负值,如果为负值,则重置为"水平容差":

    bool Approximate(vector<PointC*>* pOutput, LineC input, double horizontalTolerance, double verticalTolerance=-1)
    {
        if (verticalTolerance < 0)
        {
            verticalTolerance = horizontalTolerance;
        }
        // Rest of function
    }
    

在我看来,第一点不是解决方案,而是旁路,第二点不可能是最简单的解决方案。

或者

你可以使用重载:

bool Approximate(vector<PointC*>* pOutput, LineC input, 
                     double horizontalTolerance, double verticalTolerance)
{
//whatever
}
bool Approximate(vector<PointC*>* pOutput, LineC input, 
                     double tolerance)
{
   return Approximate(pOutput, input, tolerance, tolerance);
}

这完美地模仿了您想要实现的目标。