Structured binding to access multiple return values
In C++ quite often you may want to return multiple values from a function and access it afterward. Here are few options for how things were done before C++ 17 structured binding was introduced.
Let's say we have a function like this that returns three values.
std::tuple<std::string, int, double> getDataPosition(){ // some code returning multiple values return {"NQ", 100, 4455.98}; }
For accessing the data you can access it using std::tuple and std::get
std::tuple<std::string, int, double> positionData = getDataPosition(); // or auto.. std::string symbol = std::get<0>(positionData); int volume = std::get<1>(positionData); double price = std::get<2>(positionData);
It is quite messy and there was a better way using std::tie
std::string symbol; int volume; double price; std::tie(symbol, volume, price) = getDataPosition()
Notice you have to declare variable types in advance, not in the std:tie. From C++ 17 we can access it directly in one line using structured binding.
auto[symbol, volume, price] = getDataPosition();
This is way cleaner. The compiler does all its unpacking and figuring the types. Notice that you cannot declare variable types in advance. This will not work.
std::string symbol; int volume; double price;
auto[symbol, volume, price] = getDataPosition();