Florian
Florian

Reputation: 13

How to infer automatically the size of a C-Array within a struct template?

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?

Upvotes: 1

Views: 382

Answers (1)

Jarod42
Jarod42

Reputation: 217275

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

Upvotes: 4

Related Questions