存储函数指针的正确语法

17 c++ function-pointers implicit-conversion

令人惊讶的是,无论在函数名之前使用什么符号,以下代码在 gcc 和 clang 中都能很好地编译:*&或者什么都不用。标准是否允许其中任何一个?存储函数指针的首选方法是什么?

#include <stdio.h>

typedef int foo(int a);

template <typename X>
int g(int y) {
    return y * sizeof(X);
}

int main() {

    foo* xxx;

    // 1. what is correct according to standard?
    // 2. why they all work?
    xxx = *g<float>;
    xxx = &g<float>;
    xxx = g<float>;

    printf("ok %d\n", xxx(5));
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 14

一切都应该正常工作,并在此处具有相同的效果。首选哪个是样式问题,IMO 代码中的第一个令人困惑,另外两个是非常常见的用法。

为方便起见,我将按照与您的代码相反的顺序进行解释,

  1. 对于xxx = g<float>;,从 执行函数到指针的隐式转换g<float>,将转换后的指针分配给xxx

  2. 对于xxx = &g<float>;,operator&显式用于获取函数的地址,返回的指针被分配给xxx

  3. 对于xxx = *g<float>;,从 执行函数到指针的隐式转换g<float>,然后由 取消对指针的引用operator*,返回一个函数引用,在其上(再次)执行函数到指针的隐式转换xxx,最后将转换后的指针分配给。