简体   繁体   中英

C++ ADL: Call a function from the namespace which a particular type belongs to

Imagine there is an existing type Inner in its own namespace. In this namespace there is a function/operator ( myfunc ) taking in the Inner type. Suppose, this function doesn't work properly, but we can't change it. Next, the type Inner is aliased within another class ( G ). That class belongs to a different namespace and defines a proper version of myfunc there. There is also a class template parametrized by G . When it calls myfunc ADL automatically selects the namespace of Inner . Is it possible to tell the compiler that it should call myfunc from the namespace of G ?

namespace ns1
{
    template <class T>
    class F
    {
    public:
        F()
        {
            typename T::I inner;

            // myfunc() is declared both in the namespace of T and T::I.
            // ADL picks up the innermost, i.e. T::I. Is it possible to 
            // tell the compiler that myfunc() must be selected from the 
            // namespace of T?
            myfunc(inner);
        }
    };
}

namespace ns3
{
    class Inner { };

    void myfunc(const Inner& i) {}
}

namespace ns2
{
    class G
    {
    public:
        using I = ns3::Inner;
    };
}

int main()
{
    ns1::F<ns2::G> f;
}

Generally speaking, is there any way in C++ to access the namespace of a particular entity? Eg namespace_of(SomeClass)::function_in_that_namespace() .

Is it possible to tell the compiler that it should call myfunc from the namespace of G ?

No.

Generally speaking, is there any way in C++ to access the namespace of a particular entity? Eg namespace_of(SomeClass)::function_in_that_namespace() .

No.


You'll have to find a different approach, such as wrapping myfunc in another function, that uses ADL to call myfunc by default, but can be overloaded. Or something similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM