【问题标题】:Implicit cast from function to function pointer?从函数到函数指针的隐式转换?
【发布时间】:2019-06-18 20:31:21
【问题描述】:

我有一个函数,它接受一个函数指针作为参数。令人惊讶的是,我既可以传入函数指针,也可以传入普通函数:

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

我很困惑为什么会这样。是否存在从函数到函数指针的隐式转换?

【问题讨论】:

  • 而且,由于地址和取消引用规则对函数起作用的方式,您还可以使用 &amp;&amp;f&amp;&amp;&amp;f 等,与任意数量的 & 一起使用。同样,在apply 中,您可以写成(*f)(n)(**f)(n) 等。

标签: c++ function function-pointers


【解决方案1】:

是的,有function-to-pointer implicit conversion

函数类型 T 的左值可以隐式转换为纯右值 pointer to that function。这不适用于非静态成员函数,因为不存在引用非静态成员函数的左值。

函数指针可以用非成员函数或静态成员函数的地址初始化。由于函数到指针的隐式转换,地址操作符是可选的:

void f(int);
void (*p1)(int) = &f;
void (*p2)(int) = f; // same as &f

这意味着在需要函数指针的上下文中使用时,函数(非静态成员函数除外)将隐式转换为函数指针,operator&amp; 的使用是可选的。

【讨论】:

    猜你喜欢
    • 2018-09-25
    • 2022-08-24
    • 2016-08-18
    • 2013-11-03
    • 2015-11-03
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多