I've written a template code that takes a functor as an argument and after some processing, executes it. Although someone else might pass that function a lambda, a function pointer or even an std::function
but it is meant primarily for lambda(not that I ban other formats). I want to ask how should I take that lambda - by value? by reference? or something else.
Example code -
#include <iostream>
#include <functional>
using namespace std;
template<typename Functor>
void f(Functor functor)
{
functor();
}
void g()
{
cout << "Calling from Function
";
}
int main()
{
int n = 5;
f([](){cout << "Calling from Temp Lambda
";});
f([&](){cout << "Calling from Capturing Temp Lambda
"; ++n;});
auto l = [](){cout << "Calling from stored Lambda
";};
f(l);
std::function<void()> funcSTD = []() { cout << "Calling from std::Function
"; };
f(funcSTD);
f(g);
}
In above code, I've a choice of making it either of these -
template<typename Functor>
void f(Functor functor)
template<typename Functor>
void f(Functor &functor)
template<typename Functor>
void f(Functor &&functor)
What would be the better way and why? Are there any limitations to any of these?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…