如何在 C++ 中获取在 class 主体中定义为友元的重载运算符的地址

How to take address of an overloaded operator defined as a friend in class body in C++

如何获取定义为 class 正文中友元的重载运算符的地址?

我尝试了以下方法

struct S {
  friend bool operator==(S, S) { return true; }
};

int main() {
  bool (*f)(S, S) = &operator==;
}

但是gcc报错

test.cc: In function ‘int main()’:
test.cc:6:30: error: ‘operator==’ not defined
   bool (*f)(S, S) = &operator==;
                              ^

可以通过在(全局)命名空间中声明运算符来修复:

bool operator==(S, S);

有没有办法在不重新声明运算符的情况下获取地址?

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

http://en.cppreference.com/w/cpp/language/friend,强调我的。

一般来说,你应该始终在 class 之外声明你的朋友,除非你明确地希望将他们隐藏在除了 ADL 之外的任何查找中(这可能是个好主意,也可能不是,我不有足够的经验来判断,这真的要视情况而定。)。

Is there a way to take the address without redeclaring the operator?

不行,名字在class的范围内,不能直接使用

从标准,11.3$6,7朋友[class.friend](我加粗)

6 A function can be defined in a friend declaration of a class if and only if the class is a non-local class (9.8), the function name is unqualified, and the function has namespace scope.

7 Such a function is implicitly inline. A friend function defined in a class is in the (lexical) scope of the class in which it is defined. A friend function defined outside the class is not (3.4.1).