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

如何从函数指针类型提取签名并构造std::function对象?

利用函数指针类型构造std::function对象

当你定义的FType是函数指针类型(int(*)(int,int))时,不能直接把它传给std::function的模板参数——因为std::function需要的是函数签名类型(比如int(int,int)),而不是函数指针类型。

解决方法很直接:用类型萃取工具去掉指针修饰,提取出原始的函数签名类型即可。

具体实现步骤

  1. 包含必要的头文件:
#include <functional>   // 用于std::function
#include <type_traits>  // 用于std::remove_pointer_t
  1. 定义你的函数指针类型:
using FType = int(*)(int,int);
  1. 构造std::function对象:
// 先写一个符合签名的测试函数
int add(int a, int b) {
    return a + b;
}

// 用std::remove_pointer_t提取FType对应的函数签名类型
std::function<std::remove_pointer_t<FType>> func = add;

// 调用测试
func(2, 3);  // 返回5

补充说明

  • 如果你的编译器不支持C14的std::remove_pointer_t(别名模板),可以改用C11的基础版本:
std::function<typename std::remove_pointer<FType>::type> func = add;
  • 不要直接写std::function<FType>,这会创建一个存储函数指针的std::function,而非存储符合签名的任意可调用对象(比如lambda、仿函数),不符合常规需求。

内容的提问来源于stack exchange,提问作者asmbaty

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:15:52