Boost logo

Boost :

From: Richard Hodges (hodges.r_at_[hidden])
Date: 2022-06-23 21:19:40


On Fri, 3 Jun 2022 at 09:19, Julien Blanc <julien.blanc_at_tgcm.eu> wrote:

> Le 2022-06-03 08:44, Richard Hodges via Boost a écrit :
> > On Fri, 3 Jun 2022 at 08:31, Julien Blanc via Boost
> > <boost_at_[hidden]>
> > wrote:
> >
> > Are you able to provide one or two motivating use cases? i.e. scenarios
> > in
> > which I would strongly prefer to use this library rather than a
> > std::array
> > and static_cast?
>
> You mean, in addition to
> https://github.com/julien-Blanc-tgcm/indexed_array#sample-use-cases ?
>
>
Yes, I'm looking for a real-world use case. The trivial hypothetical cases
offered are building a static association between an enum value and some
other value.
This can be done with switch/case (for example), in about the same amount
of typing, at compile time, in a function.

For example:

constexpr std::uint32_t
base_address(i2c_id id)
{
    switch(id)
    {
        case i2c_id::i2c1: return 0x1060000u;
        case i2c_id::i2c2: return 0x1070000u;
        case i2c_id::i2c3: return 0x1080000u;
        case i2c_id::i2c4: return 0x1090000u;
    }
}

constexpr std::uint32_t
offset(i2c_register r)
{
    switch(r)
    {
        case i2c_register::set_clock: return 0;
        case i2c_register::read: return 1;
        case i2c_register::write: return 2;
        case i2c_register::ack: return 3;
    }
}

https://godbolt.org/z/bYYq65hc6

Another benefit that i did not speak of is that you get type safety for
> the index. i.e. you cannot use a wrongly typed index:
>
> indexed_array<char const*, user_messages> messages;
> std::array<char const*, nb_user_messages> messages_arr;
> // ...
> play_message(messages_arr[static_cast<int>(tech_message::goon)]); //
> boom at runtime
> play_message(messages[tech_message::goon]); // fails to compile
>
> I also find the code clearer (the static_cast just adds noise in my
> opinion), but that would be a matter of taste.
>
> Regards,
>
> Julien
>


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk