MSalters notes that "non-capturing lambda can be converted to a function pointer." What does it mean? The lambda object will correspond to a pointer to the type of the function parameter.
It's hard to translate a lambda type to a function pointer. Here is my attempt to implement a compatible implementation. It hacked a bit.
#include <type_traits> template< typename fn > struct ptmf_to_pf; template< typename r, typename c, typename ... a > struct ptmf_to_pf< r (c::*) ( a ... ) const > { typedef r (* type)( a ... ); }; // Use SFINAE to hide function if lambda is not convertible to function ptr. // Only check that the conversion is legal, it never actually occurs. template< typename lambda > typename std::enable_if< std::is_constructible< typename ptmf_to_pf< decltype( &lambda::operator() ) >::type, lambda >::value >::type f( lambda arg ) { arg( "hello " ); arg( "world\n" ); }
This will not accept function pointers as direct arguments, since the template parameter must be resolved to a functor. You can do this by providing a specialization for ptmf_to_pf
, which accepts a pointer to function types.
In addition, as the demo shows, it will not accept lambdas that capture anything by value, as well as by reference. In C ++, there is no way to make the restriction so specific.
source share