我在实用程序名称空间中定义了以下静态函数。
class InvalidDecimalPlace {};
namespace utilities
{
double static RoundToNthDecimalPlace(double number, int decimalPlace)
{
if (decimalPlace < 0 )
throw InvalidDecimalPlace();
else if (decimalPlace == 0)
return static_cast<int>(number);
int powerUp = std::pow(10, decimalPlace);
number *= powerUp;
int numberWithoutDecimals = static_cast<int>(number);
return numberWithoutDecimals / static_cast<double>(powerUp);
}
};
在另一个文件中,我想对该函数进行别名处理,因此不需要使用范围解析运算符对其进行限定。有人叫我执行以下操作:
auto& RoundToNDecimalPlace = utilities::RoundToNthDecimalPlace;
// Or the following, const auto RoundToNDecimalPlace = utilities::RoundToNthDecimalPlace;
尽管我注意到这仅适用于auto
。为什么会这样呢?例如,为什么以下各项不起作用?
double& RoundToNDecimalPlace = utilities::RoundToNthDecimalPlace;
该函数的类型不是double
,而是double (&) (double, int)
,我认为这是使用auto
时的最终结果。但是函数的名称会变成一个指针,因此“通常”的方法(从C继承)将是创建指向该函数的指针,如下所示:
double (*fn)(double, int) = utilities::RoundToNthDecimalPlace;
现在您可以像使用原始功能一样使用`find:
double result = fn(1.0, 3);
由于Utilities::roundToNthDecimalPlace
是一个函数,其类型为
double (double, int);
这是接受双精度值并返回int的函数类型。请注意,这与double类型不同,因此您无法将double&
类型的引用绑定到该类型。
当使用auto&
时,C ++正确地是要作为变量的类型
double (&) (double, int)
这是对函数的引用,该函数接受一个double值,然后返回一个int值,然后返回一个double值。
话虽如此,这里不需要使用引用变量。如果您希望能够更简洁地访问该功能,请说
using Utilities::roundToNthDecimalPlace;
希望这会有所帮助!