可以引用定义在结构体内部的友元操作符吗?

Can you refer to a friend operator defined inside a struct?

本文关键字:友元 操作符 内部 结构体 引用 定义      更新时间:2023-10-16

使用友元操作符:

struct Foo {
  friend Foo operator+(Foo, Foo) { return {}; }
};
// which is synonymous to the slightly less pretty:
struct Bar {
  friend Bar operator+(Bar, Bar); // optional
};
inline Bar operator+(Bar, Bar) { return {}; }

我基本上想要operator+的函数指针用于Foo

使用Bar,我可以这样说:

auto fn = static_cast<Bar (*)(Bar, Bar)>(&operator+);
fn({},{});

但是,如果我对Foo版本做同样的操作,g++和clang++通知我:

// g++ 4.8.3
error: ‘operator+’ not defined
   auto f = static_cast<Foo (*)(Foo, Foo)>(&operator+);
                                                    ^
// clang++ 3.2-11
error: use of undeclared 'operator+'
  auto f = static_cast<Foo (*)(Foo, Foo)>(&operator+);
                                           ^

这在本质上是不可能的,还是有一种方法可以引用函数?

如果友元函数仅在类定义中声明,则不能通过限定查找或非限定查找找到它,只能通过依赖参数的查找找到它。这意味着你可以调用这个函数,但是不能获取它的地址。

如果您想获取地址,那么您还需要在周围的命名空间中声明它。

或者,您可以使用lambda而不是老式的函数指针:

auto f = [](Foo f1, Foo f2){return f1+f2;}