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