从函数隐式转换为函数指针? [英] Implicit cast from function to function pointer?

查看:132
本文介绍了从函数隐式转换为函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

是的,有函数到指针的隐式转换:

函数类型T的左值可以隐式转换为prvalue 指向该值的指针功能.这不适用于非静态成员函数,因为引用非静态成员函数的左值不存在.

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.

还有

可以使用非成员函数或静态成员函数的地址来初始化指向函数的指针.由于函数到指针的隐式转换,address-of运算符是可选的:

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&的用法是可选的.

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.

这篇关于从函数隐式转换为函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆