Find free function that has been shadowed by a member function

50 views Asked by At

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.

2

There are 2 answers

1
Passer By On BEST ANSWER

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.

2
dalfaB On

To avoid the shadowing, a function with another name is needed.

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

namespace other_namespace
{
   template<class T> auto  relay_for_function( T&& t ) {
      return  function( std::forward<T>(t) );
   }

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