I used lambda function to pass it to std::condition_variable wait() function, but that is not the case. I use lambda functions that don't receive any parameters, and everything is absolutely clear for me. But I totally don't understand how is used lamdba function that have parameters list. Show lambda with parameters are used? How to pass parameters to them?
Show lambda with parameters are used? How to pass parameters to them?
It works exactly like with any other type of callable object:
#include <iostream>
int main()
{
auto l = [] (int i) { std::cout << "The answer is " << i; };
l(42);
}
Also notice, that you do not need to store a lambda in a variable in order to invoke it. The following is an alternative way to rewrite the above program:
#include <iostream>
int main()
{
[] (int i) { std::cout << "The answer is " << i; } (42);
// ^^^^
// Invoked immediately!
}
The type of a lambda function (the so-called "lambda closure") is defined by the compiler, and is a functor with a call operator whose signature is the one you specify when defining the lambda. Therefore, you call a lambda exactly as you would call a functor (i.e. exactly as you would call a function - or any callable object).
Thus, if you want to assign a lambda to an object, the best practice is to let the compiler deduce its type by using auto. If you do not want or cannot use auto, then you may:
Use function pointers for non-capturing lambdas (capturing lambdas are not convertible to function pointers). In the above case, thus, the following will also work:
#include <iostream>
int main()
{
void (*f)(int) = [] (int i) { std::cout << "The answer is " << i; };
f(42);
}
Use std::function (this is always possible, even if the lambda is capturing):
#include <iostream>
#include <functional>
int main()
{
std::function<void(int)> f = [] (int i)
{ std::cout << "The answer is " << i; };
f(42);
}
auto lambda = [] (int a, int b) { return a + b; };
assert(lambda(1, 2) == 3);
You don't even need a variable to hold your lambda -- you can call it directly:
std::cout << [](int n) { return n + 1 ; } (99) << std::endl ;
Related
Is it possible to get a (member) function pointer to a specific instantiation of a generic lambda?
I know I can do so for standard non capturing lambdas, and for abbreviated templates, but I can't seem to be able to get a member function pointer for the explicitly instantiated operator() call operator member function of the invented type for the generic lambda.
#include <iostream>
void f1( auto v) { std::cout << v << std::endl; }
int main() {
void (*pf)(int) = f1<int>; // OK
void (*pf2)(int) = [](int v) { std::cout << v << std::endl; } ; // OK
[](auto v) { std::cout << v << std::endl; }.operator() < int > (42); // OK
auto generic_template = [](auto v) { std::cout << v << std::endl; } ;
using generic_type = decltype (generic_template);
// void (generic_type::*pf3)(int) = &generic_type::operator()<int>; // fails to compile
pf(5);
}
The interest here is academic.
Edit:
As a note of interest to future readers the solutions offered to this question also apply to getting function pointers for lambdas with capture, in addition to generic lambdas. For example, based on the answers :
auto generic_lambda = [](auto v) { std::cout << v << std::endl; } ;
using generic_type = decltype (generic_lambda);
void (generic_type::*pf1)(int) const = &generic_type::operator();
(&generic_lambda->*pf1)(43); // OK
int x = 5;
auto capturing_lambda = [x](int v) { std::cout << v+x << std::endl; } ;
using capturing_type = decltype (capturing_lambda);
void (capturing_type::*pf2)(int) const = &capturing_type::operator();
(&capturing_lambda->*pf2)(43); // OK
Yes, and you can omit the template arguments if they can be deduced from the type being initialized (or the result type of a cast) but since the lambda isn’t mutable the member function is const and so must be the pointer-to-member.
Is it possible to get a (member) function pointer to a specific
instantiation of a generic lambda?
Lambda's operator() is const-qualified by default, you need to add const to the member function pointer type
void (generic_type::*pf3)(int) const = &generic_type::operator();
And since pf3 is a member function pointer, please note that it need a specific lambda object and uses .* or ->* to invoke.
(generic_template.*pf3)(42);
Demo
I'm trying to return a lambda function which captures a variable from its current scope. When I don't capture a variable, the lambda function is returned and can be executed with no problem:
#include <iostream>
typedef void(*VoidLambda)();
VoidLambda get() {
VoidLambda vl = []() {
std::cout << "hello" << std::endl;
};
return vl;
};
int main()
{
get()(); //prints "hello" as expected
return 0;
}
If vl attempts to capture a variable, the compiler won't compile it anymore:
#include <iostream>
typedef void(*VoidLambda)();
VoidLambda get(const char* x) {
VoidLambda vl = [x]() { //Error: no suitable conversion function from "lambda []void ()->void" to "VoidLambda" exists
std::cout << x << std::endl;
};
return vl;
};
int main()
{
get("hello")();
return 0;
}
I have already tried casting the second lambda to VoidLambda, but the problem remains the same.
I'd like to know what the difference between the first and second lambda expression is, and how to solve the problem (i.e. return the lambda function with captures).
Lambda functions which don't capture any state are, well, stateless. Thus, it is possible to model them as a normal function. If they need to capture state that isn't true anymore: the state needs to somewhere and function pointer doesn't have a place for the state.
There are basically two alternatives:
Return the lambda function using a deduced type, e.g.:
auto get(char* x) { return [x]{ std::cout << x << "\n"; }; }
Return a type-erased representation of the lambda function:
std::function<void()> get(char* x) { return [x]{ std::cout << x << "\n"; }; }
Which one to choose depends on your needs. The second one is conceptually closer to the function pointer. The first one is more efficient but requires the function to be inline (or, at least, visible where used).
Sample:
#include "stdafx.h"
#include <functional>
#include <iostream>
#include <string>
std::function<void(int)> Foo()
{
int v = 1;
int r = 2;
auto l = [v, r](int i)
{
std::cout << v << " " << r << " " << i << std::endl;
};
return l;
}
int main()
{
auto func = Foo();
func(3);
return 0;
}
Why func(3) can pass 3 to i which is the formal argument of the lambda in Foo(). I can't think out. thanks.
TL;DR: You don't pass your argument 3 into a function Foo. You pass it to a method of an object func.
A bit more detailed explanation is below.
First of all, I would like to clarify what a lambda is. A lambda in C++ is nothing more than an anonymous functor class, so essentially just a syntactic sugar. A closure is an instance of a lambda type. However, quite often you can hear words "lambda" and "closure" being used interchangeably.
So within your function Foo() you create a closure object l
auto l = [v, r](int i)
{
std::cout << v << " " << r << " " << i << std::endl;
};
which would be technically equivalent to this code:
struct Functor
{
Functor(int v, int r) : v_(v), r_(r) {}
void operator ()(int i) const {
std::cout << v_ << " " << r_ << " " << i << std::endl;
}
private:
int v_;
int r_;
};
Functor l(v, r);
Now, on the next line you return an std::function object.
return l; // actually creates std::function<void(int)>(l) and returns it
So in your main function a func is just an object which stores copies of values v, r obtained during a call to Foo() and defines operator(), similar to the struct above.
Therefore, calling func(3) you actually invoke an object method on a concrete object func, and without syntactic sugar it looks like func.operator()(3).
Here's a live example to illustrate my point.
Hope that helps to resolve your confusion.
First off, I am still relatively new to C++11, so if I am missing anything, pardon my oversight. So what I am trying to do is basically have caller pass in a function and arbitrary # of arguments for that function, store that off and then call it asynchronously later on. And it seems there are 2 main options for this:
use std::bind to bind a std::function to its arguments (which is obtained using variadic template) and then invoke it later
convert the parameter pack into a tuple, store that and std::function, then unpack tuple into multiple args again and invoke function using that
Question is, is one way better than the other? Are there pro/cons/performance benefits of one over the other?
Thanks!
EDIT: as requested, here is a clarification, the first case is more early binding where I bind args to function as soon as caller passes them on and I store the bound func to be called later. the 2nd case is where I store func and args separately and invoke function with the args later on when it has to be called. So question is which is better performance/codesize/style/etc?
Accept a std::function<...> with the appropriate signature, store it to callback later. Let the caller decide how they prefer to create/populate the parameter. E.g.,
#include <functional>
#include <iostream>
std::function<int(int)> stored_f;
void set_callback(std::function<int(int)> f) {
stored_f = std::move(f);
}
void run_the_callback(int value) {
std::cout << stored_f(value) << '\n';
}
int f(int i) {
return i + 1;
}
int g(int a, int b) {
return a + b;
}
int main() {
// Plain old function pointer
set_callback(f);
run_the_callback(1);
// Use std::bind
set_callback(std::bind(g, 2, std::placeholders::_1));
run_the_callback(2);
// Use a lambda
set_callback([](int i){ return f(i) * g(i, i);});
run_the_callback(3);
}
Best performance - if you don't absolutely require type erasure of the callback - would be to parameterize your code on functor type. E.g.:
#include <functional>
#include <iostream>
template <typename Functor>
void do_stuff_and_callback_sometimes(Functor f) {
std::cout << f(1) << '\n';
// do some stuff, then
std::cout << f(2) << '\n';
// more work, and finally
std::cout << f(3) << "\n\n";
}
int f(int i) {
return i + 1;
}
int g(int a, int b) {
return a + b;
}
int main() {
// Plain old function pointer
do_stuff_and_callback_sometimes(f);
// Use std::bind
do_stuff_and_callback_sometimes(std::bind(g, 2, std::placeholders::_1));
// Use a lambda
do_stuff_and_callback_sometimes([](int i){ return f(i) * g(i, i);});
}
Avoiding type erasure is impossible in some situations, and in others will require you to jump through hoops. Whether or not it's worthwhile to do so is situational.
A third possibility is to move the responsibility of binding all the parameters to the caller, and only keep a std::function with the signature you intend to call.
For example:
struct Silly
{
using Callback = std::function<void()>;
void registerCallback(Callback cb) { callback_ = std::move(cb); }
Callback callback_;
};
This way it is quite obvious that it is the caller's responsibility to deal with lifetime, value vs. reference semantics for the arguments, etc.
I was reading about closures on the net. I was wondering if C++ has a built-in facility for closures or if there is any way we can implement closures in C++?
The latest C++ standard, C++11, has closures.
http://en.wikipedia.org/wiki/C%2B%2B11#Lambda_functions_and_expressions
http://www.cprogramming.com/c++11/c++11-lambda-closures.html
If you understand closure as a reference to a function that has an embedded, persistent, hidden and unseparable context (memory, state), then yes:
class add_offset {
private:
int offset;
public:
add_offset(int _offset) : offset(_offset) {}
int operator () (int x) { return x + offset; }
}
// make a closure
add_offset my_add_3_closure(3);
// use closure
int x = 4;
int y = my_add_3_closure(x);
std::cout << y << std::endl;
The next one modifies its state:
class summer
{
private:
int sum;
public:
summer() : sum(0) {}
int operator () (int x) { return sum += x; }
}
// make a closure
summer adder;
// use closure
adder(3);
adder(4);
std::cout << adder(0) << std::endl;
The inner state can not be referenced (accessed) from outside.
Depending on how you define it, a closure can contain a reference to more than one function or, two closures can share the same context, i.e. two functions can share the same persistent state.
Closure means not containing free variables - it is comparable to a class with only private attributes and only public method(s).
Yes, This shows how you could implement a function with a state without using a functor.
#include <iostream>
#include <functional>
std::function<int()> make_my_closure(int x) {
return [x]() mutable {
++x;
return x;
};
}
int main() {
auto my_f = make_my_closure(10);
std::cout << my_f() << std::endl; // 11
std::cout << my_f() << std::endl; // 12
std::cout << my_f() << std::endl; // 13
auto my_f1 = make_my_closure(1);
std::cout << my_f1() << std::endl; // 2
std::cout << my_f1() << std::endl; // 3
std::cout << my_f1() << std::endl; // 4
std::cout << my_f() << std::endl; // 14
}
I suspect that it depends on what you mean by closure. The meaning I've
always used implies garbage collection of some sort (although I think it
could be implemented using reference counting); unlike lambdas in other
languages, which capture references and keep the referenced object
alive, C++ lambdas either capture a value, or the object refered to is
not kept alive (and the reference can easily dangle).
Yes, C++11 has closures named lambdas.
In C++03 there is no built-in support for lambdas, but there is Boost.Lambda implementation.
Strictly speaking. 'Closure' is LISP only. Use Let returns lambda as last commands. 'Let Over Lambda'. This is possible only for LISP because of infinite scope with lexical scoping. I don't know any other language support this natively until know.
(defun my-closure ()
(let ((cnt 0))
(lambda ()
(format t "called : ~A times" (incf cnt)))))
You can achive similar functionality using static variables and lambdas.
#include <iostream>
#include<functional>
int main()
{
std::function<std::function<int()>()> generator_function=[]()->std::function<int()>{
static int i=0;
return [&]()->int{
return i++;
};
};
std::function<int()> iterator_function=generator_function();
std::cout<<iterator_function()<<std::endl; //1
std::cout<<iterator_function()<<std::endl; //2
std::cout<<iterator_function()<<std::endl; //3
std::cout<<iterator_function()<<std::endl; //4
return 0;
}