std :: forward and rvalue

1

I am reading about the use of std: forward, looking a bit at the examples that come on the internet. And the following doubt has arisen.

If I define the temple:

    template <typename T1, typename T2>
    void outer(T1&& t1, T2&& t2) 
    {
       inner(std::forward<T1>(t1), std::forward<T2>(t2));
    }

My question is this: How many inner funces do I need to define? Which would be?. That is, I have to define inner (&), inner (& amp; &), inner (const &, const &) or I must define all combinations of both.

    
asked by Jcpardo 02.06.2018 в 00:18
source

1 answer

1

As a first introduction to std::forward , you can check this other question

The answer to your question is ... it depends (although as a general rule we will say no, you should not create several versions of inner ).

Normally, in those cases where std::forward is used, both inner and outer are templates. In these cases there is usually a collection of functions ( inner1 , inner2 , ...) and one of them will be called based on the specialization of outer . That is, outer is just a function that allows you to abstract from the concrete call inner .

Well, depending on the concrete nature of inner , you should implement only those versions that really make sense, letting those invalid combinations generate an error at compile time.

For example, if it turns out that the first parameter should be a non-constant reference (because that parameter can be modified), it does not make sense for you to implement a version of inner with this parameter as a constant reference, since it will force to make botched things that can cause indefinite behavior:

void inner(int const& a, int const& b)
{
  static_cast<A&>(a) = b + 5;
}

const int x = 1, y = 2;
outer(x,y); // Comportamiento indefinido, x es constante

Now, if having multiple versions of inner is justified as a means to comply with the specifications of the project (for example, getting some given execution times), then it makes sense to have a limited catalog of inner different ... but this heterogeneity must be sufficiently justified.

    
answered by 04.06.2018 / 08:43
source