theCuriousOne
theCuriousOne

Reputation: 77

Extracting tuple nested in a tuple using std::tie in c++11 using standard library

There's a function whose return type is std::tuple, bool>. I would like to extract the values using std::tie directly to num1, num2 and bool_val. Please note that I want to use std library directly. I have helper code to unpack it (prefer to avoid using it if c++11 std lib already allows for something like this to be done.)

Is it possible to just use std::tie to extract the values as seen below using the standard library (cpp11)? Is the syntax wrong? I am trying to understand why it does not work.

#include <iostream>
#include <tuple>

using PosType = std::tuple<int, int>;
std::tuple<std::tuple<int, int>, bool> SomeFunc() {
    return std::make_tuple(std::make_tuple(10, 12), true);
}

int main() {
    int n1 = -1, n2 = -1;
    bool b = false;
    PosType temp;

    // This line gives compilation error. Trying to understand why this might be wrong.
    // std::tie(std::tie(n1, n2), b) = SomeFunc(); 

    std::cout << n1 << " " << n2 << " " << b << " " << std::endl;
    return 0;

}

Can someone please explain this code snippet from cppreference for me? It is a possible implementation for std::tie (https://en.cppreference.com/w/cpp/utility/tuple/tie)

template <typename... Args>
auto tie(Args&... args) {
    return std::tuple<Args&...>(args...);
}

Upvotes: 0

Views: 587

Answers (1)

kmdreko
kmdreko

Reputation: 60822

Fundamentally, std::tie() creates a tuple of references from references passed to it. The issue you are running into is that references cannot bind to temporaries. Your std::tie(n1, n2) returns a temporary std::tuple<int&, int&> and cannot be bound to std::tuple<int&, int&>& as a parameter to the next std::tie().

To make this work, you will have to make an intermediate std::tuple<int&, int&> for it to bind to:

std::tuple<int&, int&> nested = std::tie(n1, n2);
std::tie(nested, b) = SomeFunc(); 

Upvotes: 1

Related Questions