为什么std :: apply失败并带有通用函数? [英] Why does std::apply fail with a generic function?

查看:133
本文介绍了为什么std :: apply失败并带有通用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

取自 cppreference ,为什么要调用 std :: apply(add_generic,...)无法编译?有解决方法吗?

Taken from cppreference, why does the call to std::apply(add_generic, ...) fail to compile? Is there a way to fix it?

#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(快照)]错误:没有用于调用
'apply(,std :: tuple)'的匹配函数[x86-64 gcc 7(快照)]注意:无法推断出模板
参数'_Fn'

[x86-64 gcc 7 (snapshot)] error: no matching function for call to 'apply(, std::tuple)' [x86-64 gcc 7 (snapshot)] note: couldn't deduce template parameter '_Fn'


推荐答案

这在C ++ 17中并不新鲜。仅根据 std :: apply 的签名,并不能告诉您是否要通过 add_generic< int> add_generic< float> add_generic< std :: string> 或其他任何东西。知道这需要更多的上下文(特别是:它需要知道 std :: apply 将如何调用它),但是该信息在呼叫站点不可用,因此不能

This is not new in C++17. Just from the signature of std::apply, there is no telling whether you want to pass add_generic<int>, add_generic<float>, add_generic<std::string>, or anything else. Knowing that requires more context (specifically: it requires knowing how std::apply is going to invoke it), but that information isn't available at the call site and so cannot be used for template argument deduction.

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

It's possible to work around that by passing one object, and making that one object capable of calling whichever instantiation of add_generic is needed:

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

这篇关于为什么std :: apply失败并带有通用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆