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

标签 c++ scope clang friend-function

我有一个类,它有一个在类中声明和定义的友元函数,我从类中的另一个函数调用这个函数。 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/

相关文章:

c# - BSTR (COM) 的长度

javascript - 如果没有选择任何选项,则禁用按钮angularJS

c++ - 这种带有 __m256 值数组的错误代码生成是 clang 错误吗?

objective-c - 在 Objective C 中,为什么我可以在没有错误或警告的情况下将 NSArray 分配给 NSMutableArray?

c# - 在 C# 中使用 P/Invoke 注册 _set_purecall_handler 函数

c++ - 在 SQLite 中迭代一个 select 语句

c++ - 立即终止线程

javascript - 从全局范围内调用 jQuery 中的函数

Javascript 变量作用域返回未定义

Clang 常量限定的 C++ 方法