为什么 std::apply 使用泛型函数失败
Why does std::apply fail with a generic function?
取自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';
相关文章:
- 链表的泛型函数remove()与成员函数remove)
- 以特征类型作为参数的泛型函数回调
- 传递非泛型函数的最有效方法是什么?
- 泛型函数反向打印任何矢量,编译器出错
- 是否可以在C++中创建泛型函数指针?
- 将泛型函数及其参数传递给元函数
- C++ 中的泛型函数持有者
- C++ 验证使泛型函数
- 两个不同流的泛型函数
- 如何覆盖 'const T&' 和 'T&&' 的泛型函数,其中 T 可以作为引用?
- 如何创建公开泛型函数的 DLL
- 为什么 std::apply 使用泛型函数失败
- 在某个值范围内生成 BST 的泛型函数
- 无法在循环中实例化泛型函数
- MISRA C++规则 14-5-1:在与类型关联的命名空间中声明的泛型函数模板的名称
- 使用泛型函数调用打印结构的所有嵌套成员变量
- C++ 使用数组作为参数创建泛型函数
- 泛型函数是否可以用于对结构求和
- C++为所有 std::sets 编写泛型函数
- 指向类成员函数的泛型函数指针