What is the best (i.e. most performant, most versatile) way to pass a lambda function as a parameter to a function which only uses (but does not store or forward) the lambda function?
Option 1: Is passing it by const-reference the way to go?
template <typename F>
void just_invoke_func(const F& func) {
int i = 1;
func(i);
}
Option 2: Or is it better to pass it as a forwarding reference (universal reference)?
template <typename F>
void just_invoke_func(F&& func) {
int i = 1;
func(i);
}
Does the latter have any advantage over the former?
Are there any hazards with one of the solutions?
Edit #1:
Option 3: As pointed out by Yakk - Adam Nevraumont, mutable
lambdas would not work with option 1. So, what about another version that takes a non-const l-value reference:
template <typename F>
void just_invoke_func(F& func) {
int i = 1;
func(i);
}
The question is: Does option 2 have any advantage over option 3?
Edit #2:
Option 4: Another version that takes the lambda by value has been proposed.
template <typename F>
void just_invoke_func(F func) {
int i = 1;
func(i);
}