How to convert a lambda to an std::function using templates

Posted by retep998 on Stack Overflow See other posts from Stack Overflow or by retep998
Published on 2012-11-13T09:59:29Z Indexed on 2012/11/13 11:01 UTC
Read the original article Hit count: 195

Filed under:
|
|
|
|

Basically, what I want to be able to do is take a lambda with any number of any type of parameters and convert it to an std::function. I've tried the following and neither method works.

std::function([](){});//Complains that std::function is missing template parameters
template <typename T> void foo(function<T> f){}
foo([](){});//Complains that it cannot find a matching candidate

The following code does work however, but it is not what I want because it requires explicitly stating the template parameters which does not work for generic code.

std::function<void()>([](){});

I've been mucking around with functions and templates all evening and I just can't figure this out, so any help would be much appreciated.

As mentioned in a comment, the reason I'm trying to do this is because I'm trying to implement currying in C++ using variadic templates. Unfortunately, this fails horribly when using lambdas. For example, I can pass a standard function using a function pointer.

template <typename R, typename...A>
void foo(R (*f)(A...)) {}
void bar() {}
int main() {
    foo(bar);
}

However, I can't figure out how to pass a lambda to such a variadic function. Why I'm interested in converting a generic lambda into an std::function is because I can do the following, but it ends up requiring that I explicitly state the template parameters to std::function which is what I am trying to avoid.

template <typename R, typename...A>
void foo(std::function<R(A...)>) {}
int main() {
    foo(std::function<void()>([](){}));
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about function