D
D
Daniil Demidko2016-06-07 10:25:42
C++ / C#
Daniil Demidko, 2016-06-07 10:25:42

Link to lambda?

The simplest lambda:

auto lsqr = [](const int &n) -> int { return n*n; };

int (*pointer)(const int&) = lsqr; // Нормально
int (&refernce)(const int&) = lsqr; // Ошибка
//Нормально, извращение
int (&perversion)(const int&) = *(int(*)(const int&)) lsqr;

Why can you make a pointer to it, but you can't make a reference?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tsarevfs, 2016-06-07
@Daniro_San

For lambdas that do not capture variables in their [], a conversion operator to a function pointer is defined (ClosureType::operator ret(*)(params)()). That's why there is an implicit cast in your 1st example. The compiler does not find a suitable conversion for the reference.
The last example first converts the lambda to a pointer and dereferences it as just a pointer.

K
kozura, 2016-06-07
@kozura

non-const lvalue reference to type int (const int&)

int n = 5;
const std::function& refernce = std::bind([](const int &n) {return n*n; }, n);
const int& x1 = refernce();  // out: x = 25

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question