从函数隐式转换为函数指针?
Implicit cast from function to function pointer?
我有一个接受函数指针作为参数的函数。令人惊讶的是,我可以同时传入函数指针和普通函数:
#include <iostream>
#include <functional>
int triple(int a) {
return 3*a;
}
int apply(int (*f)(int), int n) {
return f(n);
}
int main() {
std::cout << apply(triple, 7) << "\n";
std::cout << apply(&triple, 7) << "\n";
}
我不明白为什么会这样。是否存在从函数到函数指针的隐式转换?
是的,有 function-to-pointer implicit conversion:
An lvalue of function type T can be implicitly converted to a prvalue pointer to that function. This does not apply to non-static member functions because lvalues that refer to non-static member functions do not exist.
和
A pointer to function can be initialized with an address of a non-member function or a static member function. Because of the function-to-pointer implicit conversion, the address-of operator is optional:
void f(int);
void (*p1)(int) = &f;
void (*p2)(int) = f; // same as &f
这意味着当在需要函数指针的上下文中使用时,函数(非静态成员函数除外)将隐式转换为函数指针,operator&
的用法是可选的。
我有一个接受函数指针作为参数的函数。令人惊讶的是,我可以同时传入函数指针和普通函数:
#include <iostream>
#include <functional>
int triple(int a) {
return 3*a;
}
int apply(int (*f)(int), int n) {
return f(n);
}
int main() {
std::cout << apply(triple, 7) << "\n";
std::cout << apply(&triple, 7) << "\n";
}
我不明白为什么会这样。是否存在从函数到函数指针的隐式转换?
是的,有 function-to-pointer implicit conversion:
An lvalue of function type T can be implicitly converted to a prvalue pointer to that function. This does not apply to non-static member functions because lvalues that refer to non-static member functions do not exist.
和
A pointer to function can be initialized with an address of a non-member function or a static member function. Because of the function-to-pointer implicit conversion, the address-of operator is optional:
void f(int); void (*p1)(int) = &f; void (*p2)(int) = f; // same as &f
这意味着当在需要函数指针的上下文中使用时,函数(非静态成员函数除外)将隐式转换为函数指针,operator&
的用法是可选的。