Why does std::apply fail with a generic function, but not with a generic lambda expression?

  c++, lambda

In looking at std::apply references from cpprefrence I noticed that generic functions cannot be passed as callable objects of std::apply. Let’s consider the following generic function:

template<typename T>
T add_generic(T first, T second) { return first + second; }

we can’t call:

std::cout << std::apply(add_generic, std::make_pair(2.0f, 3.0f)) << 'n'; // Error: can't deduce the function type

Note that this is not the same question as this question. In that answer, the author writes a lambda function without template parameters, but as you know in c++20 you can have lambda expressions with template parameters. So I tried this feature to this case and surprisingly the compiler did not raise any errors.

std::apply([]<typename T>(T first,T second){
    return first+second;
},std::make_pair(2.0,3.0));

Why will the compiler be able to deduce type in the last case? Is there any difference between the two?

Source: Windows Questions C++

LEAVE A COMMENT