简体   繁体   中英

Nested Classes and ADL

Here's the code:

namespace Namespace
{
    struct L0
    {
        enum SomeEnum
        {
            EnumVal
        };

        struct L1
        {
            friend void f(SomeEnum)
            {
                std::cout << "f()" << std::endl;
            }
        };

        friend void g(SomeEnum)
        {
            std::cout << "g()" << std::endl;
        }
    };
}

int main()
{
    f(Namespace::L0::EnumVal); // error: f not defined
    g(Namespace::L0::EnumVal); // good
}

The idea here is to make the compiler find f() and g() through ADL.

However, this code fails to compile with gcc or clang. The similar code seemed to compile fine under MSVC though.

Maybe I miss something, but I don't really understand what is wrong with the code, and whether it is wrong at all. Would be nice if someone could shed some light on this one.

PS. Happy new year:)

SomeEnum is not a member of L1, so ADL does not find a function defined within L1.

I believe, this is a quote you were looking for:

A name first declared in a friend declaration within class or class template X becomes a member of the innermost enclosing namespace of X, but is not accessible for lookup (except argument-dependent lookup that considers X) unless a matching declaration at the namespace scope is provided - see namespaces for details.

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