Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between assigning to std::tie and tuple of references?

I am a bit puzzled by the following tuple business:

int testint = 1;
float testfloat = .1f;
std::tie( testint, testfloat ) = std::make_tuple( testint, testfloat );
std::tuple<int&, float&> test = std::make_tuple( testint, testfloat );

With std::tie it works, but assigning directly to the tuple of references doesn't compile, giving

"error: conversion from ‘std::tuple<int, float>’ to non-scalar type ‘std::tuple<int&, float&>’ requested"

or

"no suitable user-defined conversion from std::tuple<int, float> to std::tuple<int&, float&>"

Why? I double checked with the compiler if it's really the same type that is being assigned to by doing this:

static_assert( std::is_same<decltype( std::tie( testint, testfloat ) ), std::tuple<int&, float&>>::value, "??" );

Which evaluates as true.

I also checked online to see if it maybe was the fault of msvc, but all compilers give the same result.

like image 430
Bas Avatar asked Nov 05 '13 22:11

Bas


People also ask

What does std :: tie do?

std::tie is used to build that std::tuple of references. Using the helper function one can define all the desired comparison operators (“less than” shown below). std::tuple implements lexicographical comparison, i.e. compares the first member and based on the result it stops or continues with the second and so on.

What is the difference between tuple and pair?

The Tuple is an object capable to hold a collection of elements, where each element can be of different types. The pair can make a set of two values, which may be of different types. The pair is basically a special type of tuple, where only two values are allowed.

What is std :: tuple?

Class template std::tuple is a fixed-size collection of heterogeneous values. It is a generalization of std::pair.


1 Answers

Both make_tuple and tie will deduce the returned type by arguments. But tie will make a lvalue reference type according to deduced type and make_tuple will make an actual tuple.

std::tuple<int&, float&> a = std::tie( testint, testfloat );

std::tuple<int , float > b = std::make_tuple( testint, testfloat );

 

The goal of tie is making a temporary tuple to avoid temporary copies of tied objects, the bad effect is, you can not return a tie if entry objects are local temporary.

like image 100
masoud Avatar answered Sep 20 '22 13:09

masoud