std::tie

From cppreference.com
< cpp‎ | utility‎ | tuple
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
Elementary string conversions
(C++17)
(C++17)
 
 
Defined in header <tuple>
template< class... Types >
std::tuple<Types&...> tie( Types&... args ) noexcept;
(since C++11)
(until C++14)
template< class... Types >
constexpr std::tuple<Types&...> tie( Types&... args ) noexcept;
(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++14
std::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:

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

Example

std::tie can be used to introduce lexicographical comparison to a struct or to unpack a tuple:

#include <iostream>
#include <string>
#include <set>
#include <tuple>
 
struct S {
    int n;
    std::string s;
    float d;
    bool operator<(const S& rhs) const
    {
        // compares n to rhs.n,
        // then s to rhs.s,
        // then d to rhs.d
        return std::tie(n, s, d) < std::tie(rhs.n, rhs.s, rhs.d);
    }
};
 
int main()
{
    std::set<S> set_of_s; // S is LessThanComparable
 
    S value{42, "Test", 3.14};
    std::set<S>::iterator iter;
    bool inserted;
 
    // unpacks the return value of insert into iter and inserted
    std::tie(iter, inserted) = set_of_s.insert(value);
 
    if (inserted)
        std::cout << "Value was inserted successfully\n";
}

Output:

Value was inserted successfully

See also

Structured binding (C++17) binds the specified names to sub-objects or tuple elements of the initializer
creates a tuple object of the type defined by the argument types
(function template)
creates a tuple of forwarding references
(function template)
(C++11)
creates a tuple by concatenating any number of tuples
(function template)
(C++11)
placeholder to skip an element when unpacking a tuple using tie
(constant)