Structured binding with std::div()

23 hours ago 3

I have the following code:

int indx; ... int row = indx / 9; int col = indx % 9;

It is attractive to substitute the following:

auto [row, col] = std::div(indx, 9);

However, it's not equivalent. The problem is that in the std::div_t struct that std::div() returns, the order of quot & rem members is not specified. So in my structured binding code, it is unspecified if row and col are assigned quot & rem respectively, or the other way around. In fact, my algorithm words whether I scan my array row-wise or column-wise, so I used the structured binding construct successfully. But in general, it is not usable if you care about the order of your tuple members.

The structured binding code combined with std::div() is so attractive, it's a shame you can't rely on it in general. It's desirable for C++ features to work together in expected ways. That's what they call "orthogonality".

One possible fix is to specify the order of the div_t members. This would not break correct legacy code which refers to div_t members by name. But div() inherits from c, so changing it is not so simple.

Any thoughts?

submitted by /u/littlewing347 to r/cpp
[link] [comments]
Read Entire Article