1

i am a bit confused on the usage of std::forward with a specific use-case. Let's assume the following:

template <typename Store, typename... Args>
auto get(Store&& store, Args&&... args)
{
    return store.get(std::forward<Args>(args)...) // 1
    return std::forward<Store>(store).get(std::forward<Args>(args)...) // 2
}

Which of the //1 or //2 return statements is correct? Does it depend on the get method? (Main concern is if i have to forward the store even though i am not passing it further ahead in the call chain).

  • 4
    The difference will be in a case where (the dispatch for) calling a member function `get` will depend on whether it is called on an `lvalue` or `rvalue`. Typically, it does not make any difference. But there are ways how to define different variants of a member function for lvalues and values (so called ref-qualified member functions). See, e.g, https://stackoverflow.com/q/19474374/580083. – Daniel Langr Nov 16 '21 at 10:41

1 Answers1

0

If store is an rvalue reference, then your caller is implicotly making the promise that you are free to consume its state.

When you forward, you conditionally make the same promise to the member function get. Is that promise appropiate here? I think it is.

In practice, an rvalue overloaded get could sensibly and efficiently extract some data from the object, or skip some bookkeeping cleanup, in producing its return value.

An example of this technique is the value method on std optional.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524