3

How can we forward a function auto parameter using std::forward for the below code?

void push_value(std::vector<MyType>& vec, auto&& value)
{
    vec.emplace_back(std::forward<?>(value));
}
Michal
  • 627
  • 3
  • 13

1 Answers1

5

You want decltype(value)(value) (without forward).

Some prefer to write std::forward<decltype(value)>(value), but it does exactly the same thing, the forward is superfluous.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • While `decltype(value)(value)` is a neat trick, it doesn't really help with clarity/declaring intent. Opposed to `std::forward`ing, it will also result in a copy instead of a move when changing `auto&&` to `auto`. More info about it can be found [here](https://stackoverflow.com/a/42799658/7107236). – 303 Jun 11 '22 at 14:47
  • @303 The answer you linked to states they prefer `decltype(x)(x)`. :P I agree that `std::forward` is harder to break unintentionally, but I wouldn't use it for a non-reference intentionally (it should be `std::move`). – HolyBlackCat Jun 11 '22 at 15:45