gpt4 book ai didi

c++ - Clang:类中定义的友元函数

转载 作者:行者123 更新时间:2023-11-30 00:50:34 24 4
gpt4 key购买 nike

我有一个类,它有一个在类中声明和定义的友元函数,我从类中的另一个函数调用这个函数。 Clang 编译器 (3.3) 提示未声明友元函数的标识符。我已经用 MSVC 和 gcc 编译了这段代码,它适用于两个编译器,但现在使用 Clang 端口时我遇到了这个问题。这是该问题的一个简化示例:

class foo
{
friend void bar() {}
void asd() {bar();}
};

在 Clang 中,我得到:错误:使用未声明的标识符“bar”。如果我在类外声明/定义 pla() ,它工作正常,但我有一些宏迫使我在类内定义函数。这是 Clang 中的一些已知问题,还是 Clang 在仍然符合 C++ 标准的同时以某种方式对 C++ 名称查找更加迂腐?在类中定义/声明函数时是否有一些已知的解决方法?

最佳答案

相关规则见§7.3.1.2 [namespace.memdef]/p3:

Every name first declared in a namespace is a member of that namespace. If a friend declaration in a non-local class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by unqualified lookup (3.4.1) or by qualified lookup (3.4.3) until a matching declaration is provided in that namespace scope (either before or after the class definition granting friendship). If a friend function is called, its name may be found by the name lookup that considers functions from namespaces and classes associated with the types of the function arguments (3.4.2).

换句话说,当一个 friend 函数只在一个类中内联定义而从未在类外声明时,唯一可以找到它的方法是通过 ADL,这不适用于此处作为 bar() 没有参数。在通过非 ADL 名称查找找到函数之前,必须在最里面的封闭命名空间中有一个匹配的函数声明。

关于c++ - Clang:类中定义的友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24600050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com