【发布时间】: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