可以引用定义在结构体内部的友元操作符吗?
Can you refer to a friend operator defined inside a struct?
使用友元操作符:
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;}
相关文章:
- C++模板来检查友元函数的存在
- 模板类无法识别友元运算符
- 如何使用单独文件中的派生类访问友元函数对象
- 如何重载操作符==外模板类使用友元函数
- 对友元操作符的未定义引用
- 如何在c++中获取定义为友元的重载操作符的地址
- 模板结构中的友元操作符引发重定义错误
- 带友元操作符的模板类中的重载操作符
- 定义ostream操作符的友元函数
- 重载+=操作符作为友元函数
- 哪些c++操作符没有友元函数就不能重载
- 友元函数及其与I/O操作符的关系
- 友元操作符行为(const与非const)
- 重载大于带或不带友元的操作符
- 可以引用定义在结构体内部的友元操作符吗?
- 如何用泛型类中的友元函数重载操作符
- 没有命名空间std的友元重载操作符
- 操作符重载:从成员函数调用友元函数
- 友元函数+操作符重载
- 应该操作符声明为非成员非模板友元