c++ - 如何自动推断结构模板中 C 数组的大小?

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

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

这是交易:

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

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

在结构模板中,我存储了一个指向包含结构元素的 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 };

}

这是我的问题:

如何使用 sizeof[array]/sizeof(array [0]) 或 getArraySize 模板自动推断我的 c 数组大小的结构模板?

我想要这样的东西:

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 中推断数组大小?

最佳答案

你可以这样做:

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

Live example

关于c++ - 如何自动推断结构模板中 C 数组的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26610883/

相关文章:

c++ - C 中 ubuntu 上的性能计数器库

c# - 将 SAFEARRAY 从 C++ 返回到 C#

arrays - 将文件名存储在数组 Swift 中

java - 许多 Webapp 项目的 JSF Webapp 模板

css - 如何使用 CSS 去除滑动效果?

c++ - 当 Type 为 unique_ptr 时,为 vector 添加 operator[]

c++ - VS2017 [15.8.6]如果constexpr生成带有C2760消息的错误

具有不同方法返回类型的 C++ 模板类设计

javascript - 为什么 splice 在这个 for 循环中不起作用?

javascript - Javascript如何存储数组