[C++17] Structed Binding

in #it7 years ago (edited)

Pattern

auto [var1, var2, ...] = <pair, tuple, struct, or array expression>;


Descripton

Before C++15, when we have to get some values from certain struct, we have to make struct instance and get all struct value, then assign individual variables from each members. In C++17, we can assign member's values into variables immediately. Type can be auto, const auto, auto&, even auto&& can be. The STL's basic data structs can be accessed by using struct binding. You also can use std::tie like before, when you are using non-standard struct(which doesn't  have a pair, or doesn't make pair), when you have to get pair type. You can use std::ignore to manage unused members.


Example

std::pair<int, int> divide_remainder(int dividend, int divisor);

auto[fraction, remainder] = divide_remainder(16, 3);


One More Thing..

bool divide_remainder(int dividend, int divisor, int &fraction, int &remainder);

Many people use parameter as output to improve compile time. You don't have to do this nowadays. Recent compilers can deal with this.

Coin Marketplace

STEEM 0.20
TRX 0.25
JST 0.037
BTC 97184.44
ETH 3434.21
USDT 1.00
SBD 3.07