Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass functors by value or by C++11 Universal Reference? [duplicate]

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.

like image 867
TommiT Avatar asked Dec 19 '12 07:12

TommiT


People also ask

What is the difference between pass by reference and pass by const reference?

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.

Can you pass an rvalue by reference?

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.

What is the point of functors?

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().


1 Answers

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.

like image 90
Yuushi Avatar answered Sep 19 '22 18:09

Yuushi