creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 127034

Can you use multiple std::tie in variable declaration/initialization without repeating std::tie?

I am using std::tie to initialize some variables from a tuple like this:

int a1, a2;
std::tie(a1, a2) = tupleA;

I am wondering if it is possible to do that with multiple tuples without repeating std::tie, something along these lines:

int a1, a2, b1, b2;
std::tie(a1, a2) = tupleA,
  (b1, b2) = tupleB;

The above code does not compile. I want to have the following without repeating std::tie:

int a1, a2, b1, b2;
std::tie(a1, a2) = tupleA;
std::tie(b1, b2) = tupleB;

Other types

If I wanted to do the same with int as an example, I could easily do it:

int a = 1,
  b = 3;

I do not need to write int b; b alone is sufficient.

Is there any way to do this with std::tie?

Upvotes: 0

Views: 679

Answers (2)

Marek R
Marek R

Reputation: 38209

First of all I hate tuples.
IMO (have to stress this is my personal opinion) they are overused what leads to much less readable code.
Even in current project when I encounter tuple as a return type, I have to inspect implementation of called function to understand what is the meaning of some part of tuple.

Intention of tuples was to provide a tool to store complex data of unknown type when writing complex templates.

On the topic:

You can concatenate tuples:

auto [a1, a2, b1, b2] = std::tuple_cat(tupleA, tupleB);

but I strongly recommend you to use regular structure as return type instead the tuple.

Upvotes: 2

NathanOliver
NathanOliver

Reputation: 181068

There is not a way to do this with std::tie. std::tie is a function, not a type so you can't use the "variable creation grammar" (int a = 1, b = 3;) with it.

If you can update to C++17 you could use a structured binding to convert

int a1, a2, b1, b2;
std::tie(a1, a2) = tupleA;
std::tie(b1, b2) = tupleB;

into

auto [a1, a2] = tupleA;
auto [b1, b2] = tupleB;

Which saves you a bit of typing.

Upvotes: 2

Related Questions