C++ Logo

std-proposals

Advanced search

Re: Proposal for Explicit Index Types

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Sat, 6 Nov 2021 15:06:54 -0400
On Sat, Nov 6, 2021 at 1:54 PM Chris Kjellqvist via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Hi,
>
>
>
> I’ve been thinking about the idea of explicit types and type declaration
> for indices for data structures. The use of `int` types to index into data
> structures allows the use of one variable to multiple different data
> structures where the semantic meaning of the axis being indexed into might
> be different. A simple demonstration for this is a 2D grid with height and
> width dimensions.
>
>
>
> double sum_entries(std::vector<std::vector<double> > &my_array) {
>
> double sum = 0;
>
> for (int i = 0; I < my_array.size(); ++i) {
>
> for (int j = 0; j < my_array[i].size();
> ++j) {
>
> // BUG: swap uses of j & i
> indices
>
> sum += my_array[j][i];
>

I bet a linter like PVS-Studio can catch this bug. (If not, then that's a
deficiency in PVS-Studio! ;))

I'm confused by your use of `std::vector` in this example. For one thing,
`std::vector` is already standardized; you're definitely not going to be
able to change the "index type" of `vector` away from `size_t` at this
point. For another thing, `vector` is a 1-D data structure; it can't have
any notion of "my first index is a different type from my second index",
because it has no notion of "first" and "second" indices.
Are you proposing to change `std::vector`? and if so, how? and if not, then
eliminate it from your motivation section.

declare_free_index(idx_h)
>
> declare_free_index(idx_w)
>

This part of your proposal is known as "strong typedefs," and there is a
*lot* of literature on it. Strong typedefs are *hard*.
https://quuxplusone.github.io/blog/2018/06/12/perennial-impossibilities/#strong-typedefs
(Particularly the bulleted list A-through-K in that post.)



> using my_matrix = TwoDimMat<double, idx_h, idx_w>;
>
> sum += mat[i][j];
>
> // where mat[j][i] would
> result in a compile time error
>
>
FYI: In C++2b you'll be able to do this with much less boilerplate, by
writing
    double& operator[](RowIndex row, ColumnIndex col);
    const double& operator[](RowIndex row, ColumnIndex col) const;
and
    sum += mat[i,j];

So what you've got here is basically three things:
- An unspecified relationship to std::vector.
- A macro for declaring "strong typedefs," which is *vastly* harder than
you think; see the blog post.
- The idea that confusable function parameters should use non-confusable
strong types, which is a good idea but has an unspecified relationship to
the STL.
I don't see a WG21 proposal hiding anywhere in there.

–Arthur

Received on 2021-11-06 14:07:09