Domanda

std::tuple contains, amongst others, the following constructors:

explicit tuple( const Types&... args );

template< class... UTypes >
explicit tuple( UTypes&&... args );

Both have equivalent descriptions in that they initialise each of the elements with the corresponding value in args. The only difference is that in the second the parameters are forwarded.

From what I have understood about rvalue references, I don't see why the first version is required since the same parameters could be passed into the second version. The references would be forwarded and no-one would any the wiser especially as there is no mention of move semantics.

Can anyone explain what it is that makes both constructors necessary?

È stato utile?

Soluzione

Here is a simplified example:

template <typename T>
struct foo
{
    foo(const T&);
    template <typename U>
    foo(U&&);
};

The second constructor requires some kind of template type deduction. This doesn't work in all cases, e.g. with initializer lists. The following initialization only works, if the first constructor is available:

auto f = foo<std::vector<int>>{ { 1, 2, 3 } };

Altri suggerimenti

This is for RValue reference forwarding, and is optimized for move construction. The first version is used for lvalues. See the following link to better explain.

http://thbecker.net/articles/rvalue_references/section_07.html

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top