I define a method like so:
template <class ArgT>
void foo(ArgT arg, ::boost::function< void(ArgT) > func)
{
func(arg);
}
and use it like this –for instance–:
foo(2, [](int i) -> void { cout << i << endl; });
Why can’t the compiler deduce the type since it’s definitely an int?
I get 'void foo(ArgT,boost::function<void(ArgT)>)' : could not deduce template argument for 'boost::function<void(ArgT)>' from 'anonymous-namespace'::<lambda0>'.
While C++ lambdas are strictly monomorphic, they are merely shorthand for function objects (aka functors), and in general functors can be polymorphic; i.e., their call operators can be overloaded or templated. As a result, functors (and, consequently, lambdas) are never implicitly convertible to templated
std::function<>(orboost::function<>) instances because functors’operator()argument types are not automatically inferable.To phrase it slightly differently, the natural type of your lambda expression is a functor with a parameterless constructor and an
operator()with the signaturevoid operator ()(int) const. However obvious this fact may be to you and I, it’s not automatically inferrable thatArgTshould resolve tointbecause lambdas are functors and functors’operator()s are possible to overload and template.TL;DR: What you want isn’t possible.