I recently needed to write some code that throws a compilation error
when passing a lambda to a function that may throw an exception.
For handling the lambda args, we had this class that takes an std::function
template argument. Consider something like:
#include <functional>
template < typename Function = std::function<void()> >
void do_something(Function f)
{
f();
}
int main(int, char*[])
{
do_something([](){
throw std::exception(); // throw error here
});
return 0;
}
The first thing that comes to mind would be to throw in a noexcept specifier
like std::function<void() noexcept> - but that won't work because
std::function 's () operator would discard it. Instead the solution is to
avoid std::function all togeather and add in a static_assert like so: