std::tie - cppreference.com

From cppreference.com

template<class...Types>std::tuple<Types&...>tie(Types&...args)noexcept;(since C++11)
(constexpr since C++14)Creates a tuple of lvalue references to its arguments or instances of

std::ignore

.

Parameters

args - zero or more lvalue arguments to construct the tuple from. Return value

A

std::tuple

object containing lvalue references.

Possible implementation

template<typename...Args>constexpr// since C++14std::tuple<Args&...>tie(Args&...args)noexcept{return{args...};}Notes

std::tie may be used to unpack a

std::pair

because

std::tuple

has a

converting assignment

from pairs:

boolresult;std::tie(std::ignore,result)=set.insert(value);Example

1) std::tie can be used to introduce lexicographical comparison to a struct or to unpack a tuple;
2) std::tie can work with

structured bindings

:

Run this code

#include<cassert>#include<iostream>#include<set>#include<string>#include<tuple>structS{intn;std::strings;floatd;friendbooloperator<(constS&lhs,constS&rhs)noexcept{// compares lhs.n to rhs.n,// then lhs.s to rhs.s,// then lhs.d to rhs.d// in that order, first non-equal result is returned// or false if all elements are equalreturnstd::tie(lhs.n,lhs.s,lhs.d)<std::tie(rhs.n,rhs.s,rhs.d);}};intmain(){// Lexicographical comparison demo:std::set<S>set_of_s;Svalue{42,"Test",3.14};std::set<S>::iteratoriter;boolis_inserted;// Unpack a pair:std::tie(iter,is_inserted)=set_of_s.insert(value);assert(is_inserted);// std::tie and structured bindings:autoposition=[](intw){returnstd::tuple(1*w,2*w);};auto[x,y]=position(1);assert(x==1&&y==2);std::tie(x,y)=position(2);// reuse x, y with tieassert(x==2&&y==4);// Implicit conversions are permitted:std::tuple<char,short>coordinates(6,9);std::tie(x,y)=coordinates;assert(x==6&&y==9);// Skip an element:std::stringz;std::tie(x,std::ignore,z)=std::tuple(1,2.0,"Test");assert(x==1&&z=="Test");}See also