C ++ function in namespace won't work?

This is weird and I'm trying to find a reason why the first call to the Draw

object is shape

fine and the second call to Draw on the "text" field will only work when supplying a namespace prefix? (i.e. Shapes::Draw

):

#include <iostream>
namespace Shapes
{
    class Shape {
        public:
            Shape() {}
            virtual void InnerDraw() const {
                std::cout << "Shape\n";
            }
    };

    class Square : public Shape {
        public:
            void InnerDraw() { std::cout << "Square\n"; }
    };

    void Draw(char* text) { std::cout << text; }

    void Draw(const Shape& shape) {
        Draw("Inner: ");
        shape.InnerDraw();
    }

    Shape operator+(const Shape& shape1,const Shape& shape2){
        return Shape();
    }
}


int main() {
    const Shapes::Square square;
    Shapes::Shape shape(square);

    Draw(shape); // No need for Shapes::
    Draw("test"); // Not working. Needs Shapes:: prefix

    return 0;
}

      

+3


source to share


2 answers


For the Draw(shape)

compiler, it looks at the namespace in which the type is shape

defined to see if there is a matching function named Draw

. He finds it and calls it. There is Draw("test")

no namespace for for argument, so there is nothing else to look for. This is called search argument dependent , ADL for short.



+3


source


This is called argument-dependent search . When an unqualified function is called, the compiler looks at the namespaces for all the function arguments and adds any matching functions to the overload set. So when you say Draw(shape)

it finds Shapes::Draw(const Shapes::Shape& shape)

based on the argument shape

. But when you say the Draw("test")

argument "test"

has no namespace, of course no namespace is required Shapes::

.



+2


source







All Articles