I have the following templated function (C++ latest standard is enabled in the compiler - but maybe 17 would be enough).
#include <functional>
template<typename TReturn, typename ...TArgs>
void MyFunction(const std::function<TReturn(TArgs...)>& callback);
int main()
{
MyFunction(std::function([](int){}));
MyFunction([](int){});
}
The first call compiles, when I explicitly convert it to std::function, but the second case does not.
In the first case the template deduction is done automatically, the compiler only knows that it shall convert it to some std::function and able to deduce the parameter and return type.
However in the second case it shall(?) also know that the lambda shall be converted to some std::function, but still unable to do it.
Is there a solution to get the second one running? Or can it be that for templates the automatic conversion does not take place at all?
The error message is:
error C2672: 'MyFunction': no matching overloaded function found
error C2784: 'void MyFunction(const std::function<_Ret(_Types...)> &)': could not deduce template argument for 'const std::function<_Ret(_Types...)>
note: see declaration of 'MyFunction'
What I am aiming for is a "python style decorator". So basically this:
template<typename TReturn, typename ...TArgs>
auto MyFunction(std::function<TReturn(TArgs...)>&& callback) -> std::function<TReturn(TArgs...)>
{
return [callback = std::move(callback)](TArgs... args)->TReturn
{
return callback(std::forward<TArgs>(args)...);
};
}
If I used a template instead of std::function, the how would I deduce the parameter pack and return value? Is there some way to get it from a callable via some "callable traits"?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…