lambda to std::function template

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'?
What would be the point? What problem would Convert() solve?
Do you realize that a lambda is a callable target?

http://en.cppreference.com/w/cpp/utility/functional/function

There is an example where a lambda is stored in a std::function, thereby wrapping the lambda. Is that what you are after?

Good Luck :+)
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
@JLBorges

Thank you. You have helped me so many times.

Can you introduce yourself or give me a website link of your blog?
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).
Topic archived. No new replies allowed.