19

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.

Community
  • 1
  • 1
TommiT
  • 609
  • 3
  • 9
  • The templates are expanded/resolved at compile time. How can they know about the state at the compile time? – Manoj R Dec 19 '12 at 07:16
  • 2
    Note that with the first one you can always use a reference-wrapper to avoid a copy. – Björn Pollex Dec 19 '12 at 07:18
  • @Manoj R: What I meant was: You have a function object variable fn_obj, you call apply(fn_obj), and then you have access to fn_obj.state, which might have been modified by the call to apply – TommiT Dec 19 '12 at 07:26

1 Answers1

8

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.

Yuushi
  • 25,132
  • 7
  • 63
  • 81