简体   繁体   English

嵌套类和ADL

[英]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. 这里的想法是让编译器通过ADL找到f()和g()。

However, this code fails to compile with gcc or clang. 但是,此代码无法使用gcc或clang进行编译。 The similar code seemed to compile fine under MSVC though. 类似的代码似乎在MSVC下编译正常。

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. PS。 Happy new year:) 新年快乐:)

SomeEnum is not a member of L1, so ADL does not find a function defined within L1. SomeEnum不是L1的成员,因此ADL找不到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. 在类或类模板X中的友元声明中首先声明的名称成为X的最内层封闭命名空间的成员,但是无法进行查找(除了与X相关的依赖于参数的查找),除非命名空间范围内的匹配声明是提供 - 请参阅命名空间以获取详细信

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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