Nested Classes and ADL

房东的猫 提交于 2019-12-10 18:12:36

问题


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:)


回答1:


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.



来源:https://stackoverflow.com/questions/34550342/nested-classes-and-adl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!