mercredi 11 septembre 2019

Using std::initializer_list[] as const list of lists of varying length

I need a static const list of lists of varying length (of QPointF from Qt) that I directly initialize in my code (see below), and which is only used read-only later on.

I first used const std::vector<QPointF>[] for that, but then it ocured to me that I could just use const std::initializer_list<QPointF>[] instead (is the const even necessary?).

static const std::initializer_list<QPointF> points[6] = {
        { { 0.50f, 0.50f } },
        { { 0.25f, 0.25f }, { 0.75f, 0.75f } },
        { { 0.25f, 0.25f }, { 0.50f, 0.50f }, { 0.75f, 0.75f } },
        { { 0.25f, 0.25f }, { 0.75f, 0.75f }, { 0.25f, 0.75f }, { 0.75f, 0.25f } },
        { { 0.25f, 0.25f }, { 0.75f, 0.75f }, { 0.50f, 0.50f }, { 0.25f, 0.75f }, { 0.75f, 0.25f } },
        { { 0.25f, 0.25f }, { 0.75f, 0.75f }, { 0.25f, 0.50f }, { 0.75f, 0.50f }, { 0.25f, 0.75f }, { 0.75f, 0.25f } },
    };

Is this a valid use of std::initializer_list? It looks like a hack to me, probably because the name of std::iniatilizer_list suggests a certain use. Answers to this post also mention that initializer lists are intended to be used for, well, initialization of e.g. containers.

I also considered const std::array<...>[], but then all the inner lists have to be of the same length.

Aucun commentaire:

Enregistrer un commentaire