在查看 std::apply 的引用时参考参数 https://en.cppreference.com/w/cpp/utility/apply我们可以看到函数模板不能作为 std::apply 的可调用对象传递。让我们考虑以下函数模板:
template<typename T>
T add_generic(T first, T second) { return first + second; }
因此,由于无法在 std::apply 调用中推导函数模板,因此我们不能使用以下代码:
std::apply(add_generic, std::make_pair(2.0f, 3.0f)); // Error: can't deduce the function type
请注意,这不是同一个问题这个问题 https://stackoverflow.com/questions/43171323/why-does-stdapply-fail-with-a-generic-function。在该答案中,作者编写了一个没有显式模板参数的 lambda 表达式。
std::cout << std::apply(
[](auto first, auto second) { return add_generic(first, second); },
std::make_tuple(2.0f,3.0f)) << '\n';
但正如你所知c++20 https://en.cppreference.com/w/cpp/language/lambda您可以使用带有显式模板参数列表的 lambda 表达式。所以我尝试了这个功能,令人惊讶的是编译器没有引发任何错误。
std::apply([]<typename T>(T first,T second){
return first+second;
},std::make_pair(2.0,3.0));
为什么编译器能够在最后一种情况下推断出类型?两者有什么区别吗?