简体   繁体   中英

Ensure specific std::array position at compile time

I have an std::array with entries I want at a specific position according to the index of my Variable class at compile time:

#include <string_view>
#include <array>

struct Variable
{
  size_t index;
  std::string_view name;
}

constexpr std::array<Variable, 3> myarray {{{0, "myvar1"},
                                            {1, "myvar2"},
                                            {2, "myvar3"}}};

Now I can ensure the position at compile time with a static assert:

static_assert(myarray[0].index == 0);
static_assert(myarray[1].index == 1);
static_assert(myarray[2].index == 2);

This avoids typing errors as:

constexpr std::array<Variable, 3> myarray {{{0, "myvar1"},
                                            {2, "myvar2"}, // wrong index for array position 1
                                            {2, "myvar3"}}};

But this is error prone and violates the principle of "single source of truth". What I want is for example the reverse of std::get<T> :

constexpr std::size_t index0 = 0;
std::set<index0>(myarray, {index0, "singen"});

But this does not exist, how would I achieve this in C++17?

you might use std::get for your hypothetical std::set<index0>(myarray, {index0, "singen"}) :

constexpr std::size_t index0 = 0;
std::get<index0>(myarray) = {index0, "singen"};

But seems simpler to rework your array creation:

constexpr std::array<Variable, 3> make_myarray()
{
    std::array<Variable, 3> res{};
    std::array<std::string_view, 3> strings = {"myvar1", "myvar2", "myvar3"};

    for (std::size_t i = 0; i != res.size(); ++i) {
        res[i] = {i, strings[i]};
    }
    return res;
}

And then

constexpr std::array<Variable, 3> myarray = make_myarray();

Demo

You might even create lambda instead of regular function and call it directly:

constexpr std::array<Variable, 3> myarray = [](){
    std::array<Variable, 3> res{};
    std::array<std::string_view, 3> strings = {"myvar1", "myvar2", "myvar3"};

    for (std::size_t i = 0; i != res.size(); ++i) {
        res[i] = {i, strings[i]};
    }
    return res;
}();

Demo

or even create your check function

template <std::size_t N>
constexpr bool is_valid(const std::array<Variable, N>& a) {
    for (std::size_t i = 0; i != a.size(); ++i) {
        if (a[i].index != i) {
            return false;
        }
    }
    return true;
}

constexpr std::array<Variable, 3> myarray {{{0, "myvar1"},
                                            {2, "myvar2"}, // wrong index for array position 1
                                            {2, "myvar3"}}};

static_assert(is_valid(myarray)); // Trigger here.

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM