Implicit cast from function to function pointer?

有些话、适合烂在心里 提交于 2019-12-19 09:44:37

问题


I have a function that accepts as an argument a function pointer. Surprisingly, I can pass in both a function pointer and an ordinary function:

#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";
}

I'm confused about why this works. Is there an implicit conversion from functions to function pointers?


回答1:


Yes, there's 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.

And

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

That means when being used in context requiring a function pointer, function (except for non-static member function) would convert to function pointer implicitly, and the usage of operator& is optional.



来源:https://stackoverflow.com/questions/54357936/implicit-cast-from-function-to-function-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!