Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are implicit conversions allowed with std::tie?

In c++11, are implicit conversions allowed with std::tie?

The following code compiles and runs but I'm not sure exactly what's going on behind the scenes or if this is safe.

std::tuple<float,float> foo() { return std::make_tuple(0,0); }

double a, b;
std::tie(a,b) = foo(); // a and b are doubles but foo() returns floats
like image 459
lenguador Avatar asked Oct 26 '16 01:10

lenguador


People also ask

What does std :: tie do?

std::tie. Creates a tuple of lvalue references to its arguments or instances of std::ignore.

How does implicit conversion work c++?

Implicit Type Conversion Also known as 'automatic type conversion'. Done by the compiler on its own, without any external trigger from the user. Generally takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid lose of data.

What are implicit conversions?

An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.

What is the use of ties operator in C++?

Using a tie in C++ There are two major uses for std::tie : simple implementation for comparison operators for user defined data structures and unpacking pair/tuples (e.g. return values).


1 Answers

What happens is the template version of tuple's move-assignment operator is used

template< class... UTypes >
tuple& operator=(tuple<UTypes...>&& other );

which move-assigns individual tuple members one by one using their own move-assignment semantics. If the corresponding members are implicitly convertible - they get implicitly converted.

This is basically a natural extension of similar functionality in std::pair, which we've been enjoying for a long while already.

like image 126
AnT Avatar answered Oct 14 '22 18:10

AnT