[英]c++ two functions do the same except one line
I dont want to duplicate my code, but I have 2 functions which do the same except 1 line. 我不想重复我的代码,但是我有2个函数,除了1行外,它们的功能相同。 I do want separate functions that will call a private function, that might be a template and will solve my duplicate code problem. 我确实想要单独的函数来调用私有函数,该函数可能是模板,并且可以解决我的重复代码问题。
double EuclideanDistance::calculateDistance(const Point &p1, const Point &p2) const
{
if (p1.getDimension()!=p2.getDimension())
return 0;
double sum = 0.0;
for( size_t i = 0; i < p1.getDimension(); i++)
{
sum += pow( p1[i] - p2[i], 2.0);
}
return sqrt(sum);
}
double EuclideanDistance::calculateWeightedDistance(const Point &p1, const Point &p2, const double *weights) const
{
if (p1.getDimension()!=p2.getDimension())
return 0;
double sum = 0.0;
for( size_t i = 0; i < p1.getDimension(); i++)
{
sum += pow( ((p1[i] - p2[i])*weights[i]), 2.0);//here is the difference
}
return sqrt(sum);
}
what do you suggest? 你有什么建议?
Implement only calculateWeightedDistance
fully. 完全仅实现calculateWeightedDistance
。 and for calculateDistance
call calculateWeightedDistance
with weight 1.0
并为calculateDistance
调用权重为1.0
calculateWeightedDistance
What about the following? 那下面呢? If you invoke the function with the third parameter nullptr
, then the behaviour of the first version is executed. 如果使用第三个参数nullptr
调用该函数,则将执行第一个版本的行为。
double EuclideanDistance::calculateWeightedDistance(const Point& p1, const Point& p2, const double* weights) const {
if (p1.getDimension()!=p2.getDimension())
return 0;
double sum = 0.0;
for( size_t i = 0; i < p1.getDimension(); i++)
{
const auto distance_d = (p1[i] - p2[i]) *
(weights != nullptr ? weights[i] : 1.0);
sum += pow(distance_d, 2.0);
}
return sqrt(sum);
}
You may factorize this way: 您可以将这种方式分解:
template <typename F, typename Ts...>
double calculateDistanceImpl(F&& f, const Point &p1, const Point &p2, Ts&&... args)
{
if (p1.getDimension()!=p2.getDimension())
return 0;
double sum = 0.0;
for( size_t i = 0; i != p1.getDimension(); i++)
{
sum += f(p1[i], p2[i], args[i]...);
}
return sqrt(sum);
}
double EuclideanDistance::calculateDistance(const Point &p1, const Point &p2) const
{
return calculateDistanceImpl(
[](auto&& p1, auto&& p2){ return pow(p1 - p2, 2.0);},
p1, p2);
}
double EuclideanDistance::calculateWeightedDistance(const Point &p1,
const Point &p2,
const double *weights) const
{
return calculateDistanceImpl(
[](auto&& p1, auto&& p2, double weight){ return pow((p1 - p2) * weight, 2);},
p1, p2, weights);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.