C++(23):lambda可以模版参数
C++23允许在lambda中使用模版参数:
#include <iostream>
#include <string>int main()
{auto f1 = []<typename T>(T a, T b) { return a + b; };auto f2 = [](auto a, auto b) { return a + b; };std::cout << f1(10, 20) << std::endl; std::cout << f1(std::string("Hello, "), std::string("World!")) << std::endl;std::cout << f2(10, 20) << std::endl; std::cout << f2(std::string("Hello, "), std::string("World!")) << std::endl;return 0;
}
可以看到f1使用了模版参数
运行程序输出:
30
Hello, World!
30
Hello, World!可以看到f1和f2的输出是一样的,那么在lambda中使用模版有什么意义呢,我觉得最为主要的是可以约束参数a和b是同一类型的
