No lambda <<20>. std::function- this is a type eraser - it requires something destroyed, copied and invokable with a signature and erases the rest of the type.
Since your lambda cannot be copied, it cannot be saved to std::function.
(, std::shared_ptr) std::function.
#include <utility>
#include <memory>
template<class Sig>class func;
namespace details{
template<class Sig>struct inner;
template<class R,class...Args>
struct inner<R(Args...)>{
virtual ~inner() {};
virtual R invoke(Args&&...args) =0;
};
template<class F,class Sig>struct impl;
template<class F,class R,class...Args>
struct impl<F,R(Args...)>:inner<R(Args...)>{
F f;
template<class... Ts>
impl(Ts&&...ts):f(std::forward<Ts>(ts)...){}
R invoke(Args&&...args)override{
return f(std::forward<Args>(args)...);
}
};
}
template<class T>struct emplace_as{};
template<class R,class...Args>
class func<R(Args...)>{
std::unique_ptr<details::inner<R(Args...)>> pImpl;
public:
R operator()(Args...args){
return pImpl->invoke(std::forward<Args>(args)...);
}
explicit operator bool()const{return pImpl;}
func(func&&)=default;
template<class F,class...Ts,class=typename std::enable_if<
std::is_convertible<decltype(std::declval<F>()(std::declval<Args>()...)),R>::value
>::type>
func(emplace_as<F>,Ts&&...ts):
pImpl( new details::impl<F, R(Args...)>{std::forward<Ts>(ts)...} )
{}
template<class F,class=typename std::enable_if<
std::is_convertible<decltype(std::declval<F>()(std::declval<Args>()...)),R>::value
>::type>
func(F&&f):
func(
emplace_as<typename std::decay<F>::type>(),
std::forward<F>(f)
)
{}
};
- .
( : rvalue (), swap, assign emplace, typedefs result_type ..), target target_type)