Search code examples
c++name-lookupshadowing

Find free function that has been shadowed by a member function


How can I find a free function that has been shadowed by a member function in a class.

namespace some_namespace
{
    struct the_type{};
    void function(the_type);
}

namespace other_namespace
{
    template<class T>
    class my_wrapper
    {
    public:
        void function()
        { function(m_value); }
    private:
        T m_value;
    }
};

Here, I do not know in what namespace to look, so I cannot use any qualification. The implementation is expected to be found by ADL. Is the only way to escape the class by adding a wrapper function outside the class with a different name?

Why class member functions shadow free functions with same name?

Answers why it is like it is, but does not suggest what the canonical workaround is.


Solution

  • The reason ADL fails is because unqualified lookup finds my_wrapper::function. So we shadow that by bringing a dummy free function into scope.

    namespace some_namespace
    {
        struct the_type{};
        void function(the_type);
    }
    
    namespace other_namespace
    {
        struct dummy {};
        void function(dummy);
    
        template<class T>
        class my_wrapper
        {
        public:
            void function()
            {
                using other_namespace::function;
                function(m_value);
            }
        private:
            T m_value;
        };
    }
    

    † Actually, no ADL is performed.