【问题标题】:Can you refer to a friend operator defined inside a struct?你能引用在结构中定义的友元运算符吗?
【发布时间】:2014-06-12 16:04:39
【问题描述】:

使用友元运算符:

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+);
                                           ^

这本质上是不可能的,还是有办法引用该函数?

【问题讨论】:

  • 内联友元函数仅通过 ADL 可见。顺便说一句,如果你不知道,在相当多的情况下,你可以将Type{}替换为{}
  • @chris:是的,您对{} 的看法是正确的。感谢您指出。

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


【解决方案1】:

如果友元函数仅在类定义中声明,则无法通过限定或非限定查找找到它,只能通过参数相关查找找到。这意味着您可以调用该函数,但不能获取其地址。

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

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

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

【讨论】:

  • 也想到了一个 lambda,它让我觉得很奇怪,我无法引用该函数。谢谢你的解释。
猜你喜欢
  • 2011-04-30
  • 2014-10-08
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多