c++ - 您可以引用在结构中定义的友元运算符吗?

标签 c++ operator-overloading function-pointers friend-function

使用友元操作符:

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 {}; }

我基本上想要 Foooperator+ 的函数指针。

使用 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;}

关于c++ - 您可以引用在结构中定义的友元运算符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24188985/

相关文章:

c++ - 在 C++ 中使用类指针维护范围

c++ - 搜索存储在树中的数据

c++ - HDF5 hid_t obj_id? HDF5 API 与其他 hdf5 函数之间的区别

C++ 运算符意外错误

c++ - + 运算符重载以添加不同的 C++ 类对象

c++ - 使用什么代码更好地进行运算符重载

c++ - 创建字符串到函数 vector 的 HashMap

c++ - std::unordered_map 按引用传递

c - 分配作为参数传入的函数指针

c - 函数指针和函数地址