Using lambda as an argument : std::function or template?

后端 未结 2 1617
孤街浪徒
孤街浪徒 2021-01-03 02:31

I\'m studying c++11 especially interested in lambda.

After some practices, I assumed that lambda closure is an nameless function object.

So I wrote this code

相关标签:
2条回答
  • 2021-01-03 03:12

    You can't avoid it. Lambda is just a class with operator()() overloaded which executes your code. So different code - different classes.

    0 讨论(0)
  • 2021-01-03 03:13

    std::function is the generic type for lambda closures. The problem is that each lambda may capture different variables. So it can't be reduced to say a function pointer and some data, because the lambda may have captured 3 variables or it may have captured 4. std::function will take care of making sure that enough memory is allocated for the data, but it comes at a cost(the data could be heap allocated).

    However, if you are wanting to store several lambdas, and you know how many at compile-time. You could store them in an std::tuple instead. Which allows different types for each lambda. Unfortunately, C++ still doesn't provide a way to iterate over a tuple, but using Boost.Fusion you can.

    0 讨论(0)
提交回复
热议问题