Namespace + overloaded std::ostream << operator
Asked Answered
B

1

5

I'm trying to make a Vector3D class in my c++ application. For my entire program, I'm using a namespace. In this namespace I've declared my Vector3D class and an overloaded operator<< for it as such:

namespace space
{
    class Vector3D
    {
      public:
        float x, y, z;

        Vector3D(float _x = 0, float _y = 0, float _z = 0);
        Vector3D(const Vector3D & _vector);

        Vector3D & operator=(const Vector3D & _vector);
        Vector3D operator*(float _scalar);
        Vector3D operator*(const Vector3D & _vector); //CROSS PRODUCT

        float magnitude() const;
        float magnitude2() const; //FOR SPEED
        Vector3D normalize() const;
    };

    std::ostream & operator<<(std::ostream &, const Vector3D &);
}

It compiles just fine too. My problem is to cout a Vector3D, I have to manually call

space::operator<<(cout, vector);

which is a pain. I'd like to try to avoid "using namespace space;", because I like the prefix on all the rest of the objects in "namespace space".

My final question: Is there any way to call an overloaded operator function inside a namespace without using that namespace?

Thanks for the help.

Belgrade answered 7/10, 2011 at 22:41 Comment(0)
M
9

My problem is to cout a Vector3D, I have to manually call space::operator<<(cout, vector);

You don't, that's what ADL (Argument-dependent name lookup, also known as Koenig's lookup) is about. It should be enough to do

cout << vector;

If it doesn't work, either you are working with an ancient compiler or you are doing something else wrong.

Mannino answered 7/10, 2011 at 22:44 Comment(1)
Hmmm that's wierd... It must have been a makefile build issue. I rebuilt everything and it worked. Thanks :DBelgrade

© 2022 - 2024 — McMap. All rights reserved.