Didii
Didii

Reputation: 1363

Using `foo` inside definition of `bar::foo`?

How can I refer to a function foo without a namespace from within a namespace bar that has already declared that same function foo (also the same arguments)?

Minimal example

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
    }
}

I could of course rename bar::foo, but since there can be no ambiguity problem outside the namespace, I don't want to and like to keep it simple for any user.


Context

I'm trying to redefine tan to return a vector instead of a number (thus also the x-value). Here is a simplified version of what I want to do.

#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;
}

Upvotes: 1

Views: 78

Answers (2)

Captain Obvlious
Captain Obvlious

Reputation: 20083

You need to reference the type by explicitly providing it's scope. In this case the version of foo you are trying to call resides in the global namespace so you access it like so...

::foo(x);

To apply this to your code...

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

Upvotes: 5

AnT stands with Russia
AnT stands with Russia

Reputation: 320709

Function "without a namespace" actually belongs to global namespace. You can refer to it as ::foo.

Upvotes: 3

Related Questions