Oct 27, 2017 at 6:39am Oct 27, 2017 at 6:39am UTC
I want a template function('Convert') to convert a lambda to a function.
auto f1 = Convert([](){});//f1 type is std::function<void()>;
auto f2 = Convert([](int){});//f2 type is std::function<void(int)>;
auto f3 = Convert([](int&){});//f3 type is std::function<void(int&)>;
how to implement 'Convert'?
Oct 27, 2017 at 9:44am Oct 27, 2017 at 9:44am UTC
What would be the point? What problem would Convert() solve?
Oct 27, 2017 at 1:42pm Oct 27, 2017 at 1:42pm UTC
This does not work with polymorphic lambda expressions (for obvious reasons):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <iostream>
#include <functional>
#include <type_traits>
namespace detail // EDIT: make it an implementation detail
{
template < typename T > struct deduce_type ;
template < typename RETURN_TYPE, typename CLASS_TYPE, typename ... ARGS >
struct deduce_type< RETURN_TYPE(CLASS_TYPE::*)(ARGS...) const >
{ using type = std::function< RETURN_TYPE(ARGS...) > ; };
}
template < typename CLOSURE > auto wrap( const CLOSURE& fn ) // EDIT: give it a better name
{ return typename detail::deduce_type< decltype ( &CLOSURE::operator () ) >::type(fn) ; }
int main()
{
const auto f = wrap( [] ( int a ) { return a*2 ; } ) ;
static_assert ( std::is_same< decltype (f), const std::function< int (int ) > >::value, "this is insane" ) ;
std::cout << f(123456) << '\n' ;
}
http://coliru.stacked-crooked.com/a/eb5fb4031ca09844
Last edited on Oct 27, 2017 at 1:52pm Oct 27, 2017 at 1:52pm UTC
Oct 28, 2017 at 1:01pm Oct 28, 2017 at 1:01pm UTC
@JLBorges
Thank you. You have helped me so many times.
Can you introduce yourself or give me a website link of your blog?
Oct 28, 2017 at 1:46pm Oct 28, 2017 at 1:46pm UTC
I do not have a blog.
I am not a full-time employee of any organisation; I work part-time on C++ projects that arouse my interest (though my association with some of these projects have been on-going for several years).