简体   繁体   中英

Next generation of std::tie

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM