I have discovered the following behaviour with std::function
and type deduction, which was unexpected for me:
#include <functional>
template <typename T>
void stdfunc_test(std::function<T(T)> func) {};
int test_func(int arg)
{
return arg + 2;
}
int main()
{
stdfunc_test([](int _) {return _ + 2;});
stdfunc_test(test_func);
}
Both lines in main
result in error:
no instance of function template "stdfunc_test" matches the argument list
When attempting to compile in Visual Studio 2015.
Why doesn't the type deduction deduct template type from the function type, and is there a workaround for it?
No implicit conversion is performed during template argument deduction, except: temp.deduct.call
However, if the template parameter doesn't participate in template argument deduction, implicit conversion will be performed: (temp.arg.explicit)
So, if you explicitly specify the template argument, it should work:
You can use templates to deduce the signature of functions and functors:
you can try it live here: http://fiddle.jyt.io/github/d4ab355eb2ab7fc4cc0a48da261f0127