Using lambda as a parameter for std :: cout

I am experimenting using lambda and say hello when testing the next compilation.

auto lmda = [](std::ostream& os) -> std::ostream& { os << "hi"; return os; }; std::cout << lmda; 

But when you add a capture, it does not compile. Example:

 std::vector<int> v(5, 3); auto lmda = [&v](std::ostream& os) -> std::ostream& { os << v.size(); return os; }; std::cout << lmda; 

Build Error:

 In function 'int main()': 10:18: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&' In file included from /usr/include/c++/4.9/iostream:39:0, from 2: /usr/include/c++/4.9/ostream:602:5: note: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = main()::<lambda(std::ostream&)>]' operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x) 

I do not understand why in the second example this fails. Any guidance?

+7
c ++ lambda c ++ 11
source share
3 answers

A lambda without capture is converted to a function pointer that will match after overload :

 basic_ostream& operator<<( std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) ); 

As the cppreference link notes:

Calls func (* this) ;. These overloads are used to implement output I / O manipulators such as std :: endl.

from the standard section of the C ++ 11 5.1.2 project [expr.prim.lambda]:

The closure type for a lambda expression without lambda capture has a public non-virtual implicit function of converting const to a pointer for a function that has the same parameter and return types as closing the type calls the function. The value returned by this conversion function must be the address of the function, which when called has the same effect as when calling the call operator

+5
source share

Lambda without capture is converted to a pointer to a function.

[5.1.2 / 6] The closure type for a non-generic lambda expression without lambda capture has a public non-virtual implicit conversion function const for a pointer to a function with C ++ language binding (7.5) having the same parameters and return types as operator call closure function. The value returned by this conversion function must be the address of the function, which, when called, has the same effect as the close call, the operator type of the function call.

The lambda with a capture is not converted to any printed version.

+2
source share

You define a function that takes a stream, uses it, and then returns the same stream.

A possible use of this follows:

 #include <functional> #include <iostream> #include <vector> int main() { std::vector<int> v(5, 3); auto lmda = [&v](std::ostream& os) -> std::ostream& { os << v.size(); return os; }; lmda(std::cout) << std::endl; } 
0
source share

All Articles