lundi 2 janvier 2017

Returning std::make_pair with std::forward

I'm trying to create a function that will return pair containing two data types, where first type is always the same, but second is template-type. Is that even possible? (I'm also wondering if my understanding of std::forward usage is correct). For better demonstrating of my problem I'll show you simplified sample of my (not working) code.

Here's what I tried:

template <class X>
std::pair<int, X> func(X&& second)
{
    int first = 1;
    return std::make_pair(std::move(first), std::forward<X>(second));
}

Inside function, I create variable first and then I want to return pair. Here I move first - to avoid copying - and (following Scott Meyers' lecture where he explained std::forward as an "conditional move") depending if parameter second was l-value I want to pass second as an l-value (to let std::make_pair make copy of second, when creating pair) or if it was r-value I want to pass "moved" r-value.

Unfortunately my code doesn't work. I think I must have misunderstood something, but I don't know what, can you explain me, please?

Aucun commentaire:

Enregistrer un commentaire