mardi 4 février 2020

Initialization a static constexpr array in a struct with a non-const and non-static array in another struct

I'm using C++11. I have been a little fuzzy when it comes to arrays, pointer decays, and static constexpr. I might get thrashed but here we go. I am trying to use the class example as a trait class specialization by the Enum enum. I want to initialize the array in the struct example with the member arry to another existing array (called structName.member in this case). Ideally I'm trying to do this in one line, e.g. static constexpr uint8_t const (*arry)[27] = &structName::member similar to the answer for Can a method of an class (in a shared_ptr) be tied to a static function in a traits class? but I don't think I can due to const issues since member in structName isn't const or other restrictions. I know I can do it using an initializer list, but this is a bit different. I think I'm SOL in this case but I just needed to make sure.

#include <iostream>

using namespace std;

// C-style struct I'm interfacing with
typedef struct structName {
    // let's assume it gets initialized somewhere in ascending order 0..26
    uint8_t member[27]; 
} structName;

enum Enum {
    FIRST = 0,
};

template <Enum E>
struct example;

template<>
struct example<FIRST>
{
    static constexpr uint8_t const (*arry)[27] = &structName::member;
};

int main()
{
    // Want to be able to use the array as if I delcared it locally
    cout<<"value[0] %d", example<FIRST>::arry[0];

    return 0;
}

main.cpp:27:63: error: cannot convert ‘uint8_t (structName::)[27] {aka unsigned char (structName::)[27]}’ to ‘const uint8_t (* const)[27] {aka const unsigned char (* const)[27]}’ in initialization static constexpr uint8_t const (*arry)[27] = &structName::member;

Aucun commentaire:

Enregistrer un commentaire