A lambda is a unique anonymous type. The only way to name a lambda instance's type is to store it in a variable, then do a decltype
on that variable type.
There are a few ways you can catch a thrown lambda.
try {
throw []{};
} catch(...) {
}
in this case you cannot use it, other than throwing it again.
try {
throw +[]{};
} catch(void(*f)()) {
}
a stateless lambda can be converted to a function pointer.
try {
throw std::function<void()>([]{});
} catch(std::function<void()> f) {
}
you can convert it to a std::function
. The downside with std::function
is that it heap allocates for larger lambdas, which could in theory cause it to throw.
We can eliminate that heap allocation:
template<class Sig>
struct callable;
template<class R, class...Args>
struct callable<R(Args...)> {
void* state = nullptr;
R(*action)(void*, Args&&...) = nullptr;
R operator()(Args...args) const {
return action( state, std::forward<Args>(args)... );
}
};
template<class Sig, class F>
struct lambda_wrapper;
template<class R, class...Args, class F>
struct lambda_wrapper<R(Args...), F>
:
F,
callable<R(Args...)>
{
lambda_wrapper( F fin ):
F(std::move(fin)),
callable<R(Args...)>{
static_cast<F*>(this),
[](void* self, Args&&...args)->R {
return static_cast<R>( (*static_cast<F*>(self))( std::forward<Args>(args)... ) );
}
}
{}
lambda_wrapper(lambda_wrapper && o):
F(static_cast<F&&>(o)),
callable<R(Args...)>( o )
{
this->state = static_cast<F*>(this);
}
lambda_wrapper& operator=(lambda_wrapper && o)
{
static_cast<F&>(*this) = (static_cast<F&&>(o));
static_cast<callable<R(Args...)>&>(*this) = static_cast<callable<R(Args...)>&>( o );
this->state = static_cast<F*>(this);
}
};
template<class Sig, class F>
lambda_wrapper<Sig, F> wrap_lambda( F fin ) {
return std::move(fin);
}
now you can do:
try {
throw wrap_lambda<void()>([]{});
} catch( callable<void()> const& f ) {
}
callable
is "lighter weight" type erasure than std::function
as it cannot cause new heap memory to be allocated.
Live example.