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

C++20中使用std::apply调用类成员方法编译报错如何解决

报错原因

std::mem_fn 包装非静态成员函数时,调用要求第一个入参必须是对应类的实例、实例指针或实例引用(对应非静态成员函数隐含的this参数要求)。
你当前调用std::apply时传入的tuple仅包含int、double两个参数,缺少成员函数Foo::bar需要的Foo类型实例参数,导致std::__invoke找不到匹配的调用签名,触发编译报错。

解决方法

下面提供3种常用的可行方案:

  • 方案1:将当前实例指针加入tuple参数
    修改bar_apply内的调用代码,把this作为tuple的第一个元素:
    void bar_apply()
    {  
        std::apply(std::mem_fn(&Foo::bar), std::tuple<Foo*, int, double>(this, 1, 5.0));
        // 也可以用std::make_tuple简化写法:
        // std::apply(std::mem_fn(&Foo::bar), std::make_tuple(this, 1, 5.0));
    }
    
  • 方案2:使用lambda捕获当前实例,省略显式传this的步骤
    这种写法可读性更高,不需要额外记忆std::mem_fn的参数规则:
    void bar_apply()
    {  
        std::apply([this](int x, double y) {
            bar(x, y);
        }, std::tuple<int, double>(1, 5.0));
    }
    
  • 方案3:使用C++20引入的std::bind_front提前绑定this参数
    写法比std::mem_fn更简洁:
    void bar_apply()
    {  
        std::apply(std::bind_front(&Foo::bar, this), std::tuple<int, double>(1, 5.0));
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:12:03