Search code examples
c++c++03using-declaration

How to use `using space::function` in class declaration scope?


I would like to use a using declaration to enable ADL on a specific function lookup so that I can use it in a constructor initialization list.

Here is the code:

template< typename T >
struct RefWrapper
{
    RefWrapper(T& t)
    : w(t)
    {}

    T& w;
};

struct Val
{
    Val(RefWrapper<Val> rw)
    {/*...*/}
};

namespace X
{
    template< typename T >
    RefWrapper<T> MakeWrap(T& t)
    { return RefWrapper<T>(t); }
}

namespace Y
{
    using X::MakeWrap;  // god no !
    struct C
    {
        //using X::MakeWrap;  // I want it here
        //                     error: using-declaration for non-member at class scope

        C(Val& value) : member(MakeWrap(value))
        {}

        Val member;
    };
}

related:
How narrow should a using declaration be?
In this question's unique's answer, (4) is impossible, but it is the place I want !


Solution

  • Unfortunately, you can't do that.

    N4527::7.3.3$3, The using declaration, [namespace.udecl]:

    In a using-declaration used as a member-declaration, the nested-name-specifier shall name a base class of the class being defined.

    Of course, you can explicitly appoint the nested-name-specifier like:

    C(Val& value) : member(X::MakeWrap(value))
    

    Or as a workaround, you can use a local wrapper function, something like this:

    struct C
    {
        //using X::MakeWrap;  // I want it here
        //                     error: using-declaration for non-member at class scope
    
        C(Val& value) : member(MakeWrap(value))
        {}
    
        Val member;
    private:
        template< typename T >
        T MakeWrap(T& t) { return X::MakeWrap(t); }
    
    };