1

I have a question concerning how to infer automatically the size of a C-Array within a struct template. Coming from the embedded system world, I’m interested in ROMable structs in order to save RAM.

Here’s the deal:

I have many different structs like

struct  struct_1
{
    uint8_t     const   variable1;
    uint16_t    const   variable2;
};

In a struct template I store a pointer to a C-array holding struct elements and the size of that C-array, as follows.

template<typename T>
struct config_data
{
    T    const  * const  ptr_to_c_array;
    uint8_t       const  arraySize;
};

template <typename T, uint8_t array_size >
constexpr uint8_t  getArraySize ( T  (&)[ array_size ] )    
{
    return array_size;
};

int main(){

struct_1                  const  array_1[]      =  { {2,5},{1,9},{20,20} };
uint8_t                   const  arraySize_1    =  getArraySize( array_1 );
config_data <struct_1>    const  config_data_1  =  { array_1, arraySize_1 };

}

Here’s my question:

How can I have a struct template that infers the size of my c-array automatically, without giving it the size explicitly by using sizeof[array] / sizeof(array [0]) or the getArraySize template?

I’d like to have something like:

template < typename T, uint8_t  array_size >
struct config_data_new
{
    T    const  * const ptr_to_c_array;
    uint8_t       const arraySize = array_size;    //clearly, does not work   
};

int main(){

struct_1                     const  config_array_1[] =  { {2,5}, {1,9}, {20,20} };
config_data_new <struct_1>   const  config_file_new  =  { config_array_1 };           

uint8_t   const size  =  config_file_new.arraySize;

}

Is it possible to infer the array size in a template config_data _new similar to the template getArraySize?

1 Answer 1

4

You may do something like:

template <typename T, std::size_t N>
constexpr config_data<T> make_config_data(const T (&a)[N])
{
    return {a, N};
}

Live example

Sign up to request clarification or add additional context in comments.

1 Comment

Given that OP is "interested in ROMable structs in order to save RAM", you should sprinkle some constexpr around.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.