【问题标题】:How to infer automatically the size of a C-Array within a struct template?如何在结构模板中自动推断 C 数组的大小?
【发布时间】:2014-12-24 00:11:51
【问题描述】:

我有一个关于如何在结构模板中自动推断 C 数组大小的问题。 来自嵌入式系统世界,我对 ROMable 结构很感兴趣,以节省 RAM。

这是交易:

我有很多不同的结构,比如

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

在结构模板中,我存储了一个指向 C 数组的指针,该 C 数组包含结构元素和该 C 数组的大小,如下所示。

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 };

}

这是我的问题:

我怎样才能有一个结构模板来自动推断我的 c 数组的大小,而不使用 sizeof[array] / sizeof(array [0]) 或 getArraySize 模板显式地给出它的大小?

我想要类似的东西:

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;

}

是否可以在类似于模板 getArraySize 的模板 config_data _new 中推断数组大小?

【问题讨论】:

    标签: c++ arrays templates c++11 initialization


    【解决方案1】:

    你可以这样做:

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

    Live example

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2012-06-07
    • 1970-01-01
    • 2017-06-20
    • 2022-11-09
    • 1970-01-01
    相关资源
    最近更新 更多