为什么 std::apply 使用泛型函数失败

Why does std::apply fail with a generic function?

本文关键字:泛型 函数 失败 std apply 为什么      更新时间:2023-10-16

取自cpp首选项,为什么调用std::apply(add_generic, ...)编译失败?有没有办法解决它?

#include <iostream>
#include <tuple>
int add(int first, int second)
{
    return first + second;    
}
template<typename T>
T add_generic(T first, T second)
{
    return first + second;    
}
int main()
{
    std::cout << std::apply(add, std::make_tuple(1,2)) << 'n';
    // template argument deduction/substitution fails
    std::cout << std::apply(add_generic, std::make_tuple(2.0f,3.0f)) << 'n'; 
}

它失败并显示错误:

[x86-64 gcc 7(快照(] 错误:调用 to 没有匹配函数 'apply(, std::tuple(' [x86-64 gcc 7 (快照(] 注意:无法推断模板 参数"_Fn">

在 C++17 中并不新鲜。仅从std::apply的签名来看,就不知道你是要传递add_generic<int>add_generic<float>add_generic<std::string>还是其他任何东西。知道这一点需要更多的上下文(具体来说:它需要知道std::apply将如何调用它(,但该信息在调用站点上不可用,因此不能用于模板参数推断。

可以通过传递一个对象并使该对象能够调用所需的任何add_generic实例化来解决此问题:

std::cout << std::apply(
    [](auto first, auto second) { return add_generic(first, second); },
    std::make_tuple(2.0f,3.0f)) << 'n';