在`bar :: foo`的定义中使用`foo`?

Did*_*dii 1 c++ namespaces

如何foobar已经声明了相同函数foo(也是相同的参数)的命名空间中引用没有命名空间的函数?

最小的例子

int foo(int x) { // base function
    return 2*x; // multiplies input by 2
}

namespace bar {
    float foo(int x) { // same function
        return (float)foo(x); // uses same math of original, but returns a float
    }
}
Run Code Online (Sandbox Code Playgroud)

我当然可以重命名bar::foo,但由于命名空间之外不存在歧义问题,我不希望并且喜欢为任何用户保持简单.


上下文

我正在尝试重新定义tan以返回向量而不是数字(因此也是x值).这是我想要做的简化版本.

#define _USE_MATH_DEFINES // enables mathematical constants
#include <cmath> // tan

template <typename T>
struct Vector2 { // simple Vector2 struct
    T x,y;
};

namespace v2 {
    template <typename T>
    Vector2<T> tan(T angle) { // redefine tan to return a Vector2
        Vector2<T> result;
        if (-90 < angle && angle < 90)
            result.x = 1;
        else
            result.x = -1;
        result.y = tan(angle); // <-- refers to v2::tan instead of tan
        return result;
    }
}

int main() {
    double          tangens  = tan(3.*M_PI_4); // M_PI_4 = pi/4
    Vector2<double> tangens2 = v2::tan(3.*M_PI_4); // <-- no ambiguity possible

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Cap*_*ous 5

您需要通过显式提供其范围来引用该类型.在这种情况下,foo您的版本试图在全局命名空间中调用驻留,因此您可以像这样访问它...

::foo(x);
Run Code Online (Sandbox Code Playgroud)

要将此应用于您的代码......

namespace bar
{
    float foo(int x)
    { // same function
        return (float)::foo(x); // uses same math of original, but returns a float
                   // ^^ scope qualified name
    }
}
Run Code Online (Sandbox Code Playgroud)