GCC 4.7 in C++11 mode is letting me define a function taking a lambda two different ways:
// by value
template<class FunctorT>
void foo(FunctorT f) { /* stuff */ }
And:
// by r-value reference
template<class FunctorT>
void foo(FunctorT&& f) { /* stuff */ }
But not:
// by reference
template<class FunctorT>
void foo(FunctorT& f) { /* stuff */ }
I know that I can un-template the functions and just take std::functions instead, but foo is small and inline and I’d like to give the compiler the best opportunity to inline the calls to f it makes inside. Out of the first two, which is preferable for performance if I specifically know I’m passing lambdas, and why isn’t it allowed to pass lambdas to the last one?
FunctorT&&is a universal reference and can match anything, not only rvalues. It’s the preferred way to pass things in C++11 templates, unless you absolutely need copies, since it allows you to employ perfect forwarding. Access the value throughstd::forward<FunctorT>(f), which will makefan rvalue again if it was before, or else will leave it as an lvalue. Read more here about the forwarding problem andstd::forwardand read here for a step-by-step guide on howstd::forwardreally works. This is also an interesting read.FunctorT&is just a simple lvalue reference, and you can’t bind temporaries (the result of a lambda expression) to that.