Possible Duplicate:
Should templated functions take lambda arguments by value or by rvalue reference?
The C++ standard library functions take functor (function pointer or function object) arguments by value, like so:
template <typename F>
void apply(F func)
{
func();
}
...But wouldn't it be better to pass functors by Universal Reference? Like so:
template <typename F>
void apply(F&& func)
{
func();
}
This way you could pass function objects that maintain state, and have access to that (possibly modified) state after the higher-order function has returned.
From what I understand: when you pass by value, the function makes a local copy of the passed argument and uses that; when the function ends, it goes out of scope. When you pass by const reference, the function uses a reference to the passed argument that can't be modified.
You can pass an object to a function that takes an rvalue reference unless the object is marked as const . The following example shows the function f , which is overloaded to take an lvalue reference and an rvalue reference. The main function calls f with both lvalues and an rvalue.
A functor (or function object) is a C++ class that acts like a function. Functors are called using the same old function call syntax. To create a functor, we create a object that overloads the operator().
This is already the case with some algorithms; for example, in g++ 4.7.0
:
//stl_algo.h
template<typename _RandomAccessIterator, typename _UniformRandomNumberGenerator>
void
shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last,
_UniformRandomNumberGenerator&& __g)
{
...
}
Obviously, it's imperative for things such as random number generators. I imagine this will become something more common in time, however.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With