gpt4 book ai didi

c++ - 存储函数指针的正确语法

转载 作者:行者123 更新时间:2023-12-01 09:06:54 25 4
gpt4 key购买 nike

令人惊讶的是,无论在函数名前使用什么符号,以下代码在 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 代码中的第一个令人困惑,另外两个是非常常见的用法。

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

  • 对于 xxx = g<float>; , function-to-pointer implicit conversiong<float> 执行,转换后的指针被赋值给 xxx .
  • 对于 xxx = &g<float>; , operator& 显式用于获取函数的地址,返回的指针分配给 xxx .
  • 对于 xxx = *g<float>; , 函数到指针的隐式转换是从 g<float> 开始的,然后指针被 operator* 取消引用,它返回一个函数引用,在其上执行函数到指针的隐式转换(再次),转换后的指针被分配给 xxx最后。
  • 关于c++ - 存储函数指针的正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62007049/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com