嵌套类和ADL [英] Nested Classes and ADL

查看:73
本文介绍了嵌套类和ADL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

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
}

这里的想法是使编译器通过ADL找到f()和g().

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

但是,此代码无法使用gcc或clang编译.不过,类似的代码在MSVC下似乎可以很好地编译.

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.新年快乐:)

推荐答案

SomeEnum不是L1的成员,因此ADL找不到L1中定义的函数.

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:

首先在类或类模板X的朋友声明中声明的名称将成为X的最内层命名空间的成员,但不可用于查找(除非考虑X的依赖于参数的查找除外),除非在该位置使用匹配的声明提供了命名空间范围-有关详细信息,请参见命名空间.

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.

这篇关于嵌套类和ADL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆