创建函子时友元函数的可见性
请参阅下面的代码。 drive()
在范围内,我可以驾驶
保时捷
。但是,除非我取消注释 drive()
的声明,否则在尝试创建仿函数时,g++ 会给出一个非常奇怪的“drive”未在此范围内声明的错误。为什么?
#include <functional>
class car {
friend void drive(const car c);
};
//void drive(const car c);
int main() {
car porsche;
drive(porsche);
std::pointer_to_unary_function<car, void> functor(drive);
return 0;
}
更新1:我对ADL的答案几乎满意,但是我确实告诉了drive参数的类型,它是第一个模板参数,它是car:
std::pointer_to_unary_function<car, void> functor(drive);
更新2:< /strong> 好的,这是一个更简单的代码,我们不需要函子和函数头:
class car {
friend void drive(const car c);
};
//void drive(const car c) { }
int main() {
car porsche;
drive(porsche);
void (*f)(const car);
f = drive;
return 0;
}
现在,我明白为什么编译器无法使用 ADL 找到 drive
了。原因与上面相同,但是这段代码并没有被模板遮盖。
See the code below. The drive()
is in the scope, I can drive
the porsche
. However, unless I uncomment the declaration of drive()
, g++ gives a very weird ‘drive’ was not declared in this scope error when trying to create the functor. Why?
#include <functional>
class car {
friend void drive(const car c);
};
//void drive(const car c);
int main() {
car porsche;
drive(porsche);
std::pointer_to_unary_function<car, void> functor(drive);
return 0;
}
UPDATE 1: I am almost satified with the answer concerning ADL, however I did tell the type of the argument of drive, it is the first template parameter, it is car:
std::pointer_to_unary_function<car, void> functor(drive);
UPDATE 2: OK, here is an even simpler code, we do not need the functor and the functional header:
class car {
friend void drive(const car c);
};
//void drive(const car c) { }
int main() {
car porsche;
drive(porsche);
void (*f)(const car);
f = drive;
return 0;
}
Now, I understand why the compiler cannot find drive
with ADL. The reason is the same as above, but this code is not obscured by the template.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您在类中声明具有非限定 id 的
friend
函数并且该函数不是另一个类的成员时,它会在最近的封闭非类、非函数原型范围中命名一个函数。如果该函数之前尚未声明,则
friend
声明不会使该函数在该作用域中可见。但是,该函数对于参数相关查找是可见的。
在表达式
drive(porsche);
中,porsche
的类型为car
,因此使用了 ADL 并且可以找到友元函数。在表达式
drive
中没有参数,因此不执行ADL。没有可见的drive
声明,因此查找失败。When you declare a
friend
function with an unqualified id in a class and that function is not a member of another class, it names a function in the nearest enclosing non-class, non-function prototype scope.If that function hasn't previously been declared then the
friend
declaration doesn't make that function visible in that scope.However, that function is visible for argument dependent lookup.
In the expression
drive(porsche);
, theporsche
has typecar
so ADL is used and the friend function can be found.In the expression
drive
there are no arguments so ADL is not performed. There is no declaration ofdrive
visible so the lookup fails.因为朋友没有声明一个函数,而你试图调用一个不存在的全局函数。
Because friend doesn't declare a function and you're trying to call a global function which doesn't exist.