Namespaces
Variants

std:: tie

From cppreference.net
Utilities library
Definiert im Header <tuple>
template < class ... Types >
std:: tuple < Types & ... > tie ( Types & ... args ) noexcept ;
(seit C++11)
(constexpr seit C++14)

Erstellt ein Tupel von Lvalue-Referenzen auf seine Argumente oder Instanzen von std::ignore .

Inhaltsverzeichnis

Parameter

args - null oder mehr Lvalue-Argumente, aus denen das Tupel konstruiert werden soll.

Rückgabewert

Ein std::tuple Objekt, das Lvalue-Referenzen enthält.

Mögliche Implementierung

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

Hinweise

std::tie kann verwendet werden, um ein std::pair zu entpacken, da std::tuple eine konvertierende Zuweisung von Paaren besitzt:

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

Beispiel

1) std::tie kann verwendet werden, um eine lexikografische Vergleichsfunktion für eine Struktur einzuführen oder um ein Tupel zu entpacken;
2) std::tie kann mit structured bindings zusammenarbeiten:

#include <cassert>
#include <iostream>
#include <set>
#include <string>
#include <tuple>
struct S
{
    int n;
    std::string s;
    float d;
    friend bool operator<(const S& lhs, const S& 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 equal
        return std::tie(lhs.n, lhs.s, lhs.d) < std::tie(rhs.n, rhs.s, rhs.d);
    }
};
int main()
{
    // Lexicographical comparison demo:
    std::set<S> set_of_s;
    S value{42, "Test", 3.14};
    std::set<S>::iterator iter;
    bool is_inserted;
    // Unpack a pair:
    std::tie(iter, is_inserted) = set_of_s.insert(value);
    assert(is_inserted);
    // std::tie and structured bindings:
    auto position = [](int w) { return std::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 tie
    assert(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::string z;
    std::tie(x, std::ignore, z) = std::tuple(1, 2.0, "Test");
    assert(x == 1 && z == "Test");
}

Siehe auch

Structured binding (C++17) bindet die angegebenen Namen an Teilobjekte oder Tupel-Elemente des Initialisierers
(C++11)
erzeugt ein tuple -Objekt des durch die Argumenttypen definierten Typs
(Funktions-Template)
erzeugt ein tuple aus Forwarding-Referenzen
(Funktions-Template)
(C++11)
erzeugt ein tuple durch Verkettung beliebig vieler Tupel
(Funktions-Template)
(C++11)
Platzhalter zum Überspringen eines Elements beim Auspacken eines tuple mittels tie
(Konstante)