使用友元操作符:
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 {}; }
我基本上想要 Foo
的 operator+
的函数指针。
使用 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/