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

C++17/20中std::invoke调用带模板参数的Lambda失败如何解决?

解决std::invoke调用模板Lambda的编译错误

修正代码

将调用语句修改为显式指定模板成员函数的形式:

#include <bits/stdc++.h>

int main() {
    const auto func = [&]<typename T>(const std::string& h) {
        T t;
        std::cout << t << " " << h << "\n";
    };
    std::invoke(func.template operator()<std::string>, std::string("Hello"));
}

错误原因

func是存储Lambda的变量,而非模板名称。编译器遇到func<std::string>时,无法判断<是模板参数的起始符号还是小于运算符。必须通过.template关键字明确告知编译器:后续的operator()是一个模板成员函数,这样才能正确解析<std::string>作为模板实参。

替代写法

也可以先提取模板实例化后的可调用对象,再传入std::invoke:

#include <bits/stdc++.h>

int main() {
    const auto func = [&]<typename T>(const std::string& h) {
        T t;
        std::cout << t << " " << h << "\n";
    };
    auto bound_call = func.template operator()<std::string>;
    std::invoke(bound_call, std::string("Hello"));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 11:57:08