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

如何让编译器推导Lambda参数类型并传递泛型Lambda给函数?

问题:让编译器从Lambda推导出参数类型

先看这段编译失败的代码:

#include <iostream>
#include <string>

struct Bar{  };

struct Foo {
    
    template<class T>
    void setCallback(std::function<void(T)> f) {
    } 
};

int main() {
    Foo foo;
    foo.setCallback<Bar>([](Bar v) { }); // <--- 编译通过
    foo.setCallback([](Bar v) { });      // <--- 编译错误,如何修复?
}

编译时会报如下错误:

main.cpp:16:9: error: no matching member function for call to 'setCallback'
foo.setCallback([](Bar v) { }); // <--- 编译错误
^~~~~~~
main.cpp:9:10: note: candidate template ignored: could not match 'std::function<void (T)>' against '(lambda at main.cpp:16:21)'
void setCallback(std::function<void(T)> f) {
^
1 error generated.

问题核心:如何让编译器从传入的Lambda推导出其参数类型?


解决方案

通过提取Lambda的operator()成员函数类型,我们可以推导它的参数类型,具体实现代码如下:

template<typename F, typename R, typename E>
static E ArgHelper(R(F::*)(E) const);

template<typename F, typename R, typename E>
static E ArgHelper(R(F::*)(E));

struct Foo {

    template<class T>
    void setFunction(T func) {
        using Arg = decltype(ArgHelper(&T::operator()) );
        // 此处可直接使用Arg类型
    }
};

// 使用示例:
foo.setFunction([](Bar b){
    //...
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:45:11