Monday 25 December 2017

c++ - Why can't I create a vector of lambdas (of the same type) in C++11?

itemprop="text">

I was trying to create a vector of
lambda, but failed:



auto ignore =
[&]() { return 10; }; //1
std::vector v;
//2
v.push_back([&]() { return 100; });
//3


Up to line #2, it
compiles fine. But the line#3 gives
compilation
error
:






error: no matching function for call to
'std::vector>::push_back(main()::)'




I
don't want a vector of function pointers or vector of function objects. However, vector
of function objects which encapsulate real lambda expressions,
would work for me. Is this possible?


class="post-text" itemprop="text">
class="normal">Answer



Every
lambda has a different type—even if they have the same
signature. You must use a run-time encapsulating container such as
std::function if you want to do something like
that.



e.g.:




std::vector>
functors;
functors.push_back([&] { return 100;
});
functors.push_back([&] { return 10;
});

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...