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

我怕爱的太早我们不能终老 提交于 2019-12-07 05:06:20

问题


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'; 
}

It fails with error:

[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'


回答1:


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.

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';


来源:https://stackoverflow.com/questions/43171323/why-does-stdapply-fail-with-a-generic-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!