You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

函数指针与对象指针互转的编译器支持性及检测方法咨询

判断编译器对函数指针与对象指针互转的支持情况

C++标准规定函数指针与对象指针的互转属于条件支持操作,你可以通过以下两种方式判断当前编译器的支持情况及转换方向:

1. 编译期断言测试(最可靠)

直接编写编译期可验证的代码,尝试对应的转换操作,不支持的话编译器会直接报错:

测试函数指针转对象指针

// 编译期验证函数指针转对象指针是否支持
constexpr void test_func() {}
constexpr auto func_ptr_to_obj = reinterpret_cast<void*>(&test_func);
static_assert(func_ptr_to_obj != nullptr, "Function-to-object pointer conversion not supported");

测试对象指针转函数指针

// 编译期验证对象指针转函数指针是否支持
constexpr int obj = 0;
constexpr auto obj_ptr_to_func = reinterpret_cast<void(*)()>(&obj);
static_assert(obj_ptr_to_func != nullptr, "Object-to-function pointer conversion not supported");

如果编译器支持对应方向的转换,代码会正常通过编译;反之则会触发static_assert的错误提示,或者直接报错无法完成转换。

2. 编译器预定义宏判断(快速筛选)

主流编译器的支持情况可以通过预定义宏初步判断:

  • GCC/Clang:默认支持双向转换,只要定义了__GNUC__宏,基本可以认为支持该操作
  • MSVC:默认支持双向转换,可通过_MSC_VER宏判断

不过这种方式仅适用于主流编译器,对于小众嵌入式编译器,还是编译期断言的方式更准确。

内容的提问来源于stack exchange,提问作者Dr. Gut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 02:37:11