0

When a function need to return two parameters you can write it using a std::pair:

std::pair<int, int> f()
{return std::make_pair(1,2);}

And if you want to use it, you can write this:

int one, two;
std::tie(one, two) = f();

The problem with this approach is that you need to define 'one' and 'two' and then assign them to the return value of f(). It would be better if we can write something like

auto {one, two} = f();

I watched a lecture (I don't remember which one, sorry) in which the speaker said that the C++ standard people where trying to do something like that. I think this lecture is from 2 years ago. Does anyone know if right now (in almost c++17) you can do it or something similar?

bolov
  • 72,283
  • 15
  • 145
  • 224
Antonio
  • 579
  • 1
  • 3
  • 12

1 Answers1

14

Yes, there is something called structured bindings that allows for multiple values to be initialized in that way.

The syntax uses square brackets however:

#include <utility>

std::pair<int, int> f()
{
    //return std::make_pair(1, 2); // also works, but more verbose
    return { 1, 2 };
}

int main()
{
    auto[one, two] = f();
}

demo

MSalters
  • 173,980
  • 10
  • 155
  • 350
wally
  • 10,717
  • 5
  • 39
  • 72