sch*_*chc 2 c++ default-parameters
我正在编写一个近似函数,它将两个不同的公差值作为参数:
bool Approximate(vector<PointC*>* pOutput, LineC input, double horizontalTolerance, double verticalTolerance)
Run Code Online (Sandbox Code Playgroud)
如果未设置verticalTolerance,我希望函数设置verticalTolerance = horizontalTolerance.所以,我想完成以下事情:
bool Approximate(vector<PointC*>* pOutput, LineC input, double horizontalTolerance, double verticalTolerance=horizontalTolerance)
Run Code Online (Sandbox Code Playgroud)
我知道这是不可能的,因为不允许局部变量作为默认参数.所以我的问题是,设计这个功能的最佳方法是什么?
我想到的选项是:
不要使用默认参数并使用户明确设置两个容差.
将verticalTolerance的默认值设置为负值,如果为负,则将其重置为horizontalTolerance:
bool Approximate(vector<PointC*>* pOutput, LineC input, double horizontalTolerance, double verticalTolerance=-1)
{
if (verticalTolerance < 0)
{
verticalTolerance = horizontalTolerance;
}
// Rest of function
}
Run Code Online (Sandbox Code Playgroud)在我看来,第一点不是解决方案而是旁路,第二点不是最简单的解决方案.
或者你可以使用重载:
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);
}
Run Code Online (Sandbox Code Playgroud)
这完全模仿了你想要达到的目标.