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.
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.
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.
Class template std::tuple is a fixed-size collection of heterogeneous values. It is a generalization of std::pair.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With