How to forward unique_ptr with a tuple?

Imagine a function that expects rvalue references to std :: unique_ptr.

void foo(std::unique_ptr<int>&& a); 

In my example in the real world there are several arguments, so I decided to redirect the arguments to it using std::tuple<T&&> rvalue links - so std::forward_as_tuple :

 void forward_to_foo(std::tuple<std::unique_ptr<int>&&>&& t); int main() { forward_to_foo(std::forward_as_tuple(std::make_unique<int>(8))); } 

Now everything is all right.

The problem arose when I wanted to "unzip" this tuple

 void forward_to_foo(std::tuple<std::unique_ptr<int>&&>&& t) { foo(std::get<0>(t)); } 

I got this error on gcc4.9 with C ++ 14:

 error: cannot bind 'std::unique_ptr<int>' lvalue to 'std::unique_ptr<int>&&' foo(std::get<0>(t)); 

My question is: what is the problem? Why std::get<I>(t) from an rvalue link tuple return an lvalue?

+6
source share
1 answer

what is the problem?

You need std::move to go from lvalue expression:

 foo(std::move(std::get<0>(t))); 

Why std::get<I>(t) from an rvalue link tuple return an lvalue?

Because it returns an lvalue reference to a tuple element. In the general case, the result of the function returning the lvalue reference is an lvalue, since it denotes an existing object, not temporary.

+7
source

Source: https://habr.com/ru/post/983875/


All Articles