如果我有一些代码,例如:
using namespace std;
namespace myNamespace
{
vector<float> sqrt( vector<float> v ) { return v; }
void func()
{
vector<float> myVec = { 1, 2, 3, 4 };
std::cout << sqrt( myVec )[0] << std::endl;
float myFloat = 4.0f;
std::cout << sqrt( myFloat ) << std::endl; // need to use std::sqrt()
}
}
那么除非我将标记的行更改为 use ,否则它将无法编译std::sqrt
。为什么?我知道如果我尝试重新定义sqrt(float)
,那么如果我想要使用标准库版本,myNamespace
我就必须符合条件。std::
编译器似乎试图转换myFloat
而不是仅仅使用另一个 ( std
) 命名空间中的函数。
我发现解决这个问题的一种方法是sqrt(vector<float>)
在std
命名空间中定义,但这感觉不太对,对这个问题的回答表明重载std
是非法的。那时应该不会走的路……
我怎样才能重载sqrt
(或任何其他标准库 cmath 函数,就此而言),以便我不必总是限定要使用哪个并让编译器根据传递的函数参数进行选择?
谢谢。