7

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?

1
  • 3
    The second version is SFINAE-d out of overload set if not all UTypes are implicitly convertible to corresponding Types
    – jrok
    Aug 18, 2013 at 15:40

2 Answers 2

11

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 } };
0

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

2
  • 4
    The second version can be used for rvalue references as well as for lvalue references.
    – nosid
    Aug 18, 2013 at 15:38
  • Agreed but the compiler will make the best choice at compile time for function signature and in this case they have 2 signatures provided. I agree with your answer as well as it helps with template deduction and is required for that reason.
    – bjackfly
    Aug 18, 2013 at 15:45

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.