正确存储函数指针的语法

Correct syntax to store function pointer

令人惊讶的是,以下代码在 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));
}

所有应该都可以正常工作并且在这里有相同的效果。首选哪一个是样式问题,IMO 代码中的第一个令人困惑,另外两个是很常见的用法。

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

  1. 对于xxx = g<float>;function-to-pointer implicit conversion是从g<float>开始执行的,转换后的指针赋值给xxx.

  2. 对于xxx = &g<float>;operator&是显式的用来取函数的地址,返回的指针赋值给xxx.

  3. 对于xxx = *g<float>;,函数到指针的隐式转换是从g<float>执行的,然后指针被operator*解引用,returns ] 一个函数引用,在其上进行函数到指针的隐式转换(再次),转换后的指针最后赋值给xxx