简体   繁体   English

数组初始化程序必须是初始化程序列表或字符串文字

[英]array initializer must be an initializer list or string literal

What type should I use to it compile for s parameter in the constructor? 我应该使用哪种类型为构造函数中的s参数编译? I tried unsigned char s[32] and unsigned char *s but both give compiler error: 我尝试了unsigned char s[32]unsigned char *s但都给编译器错误:

array initializer must be an initializer list or string literal 数组初始化程序必须是初始化程序列表或字符串文字

struct foo
{
    size_t a;
    size_t b;
    unsigned char c[32];

    constexpr foo(size_t a_, size_t b_, ??? s) : 
        a(a_), 
        b(b_), 
        c(s)
    { 
    }

}

The closest thing you could use is variadic template: 您可以使用的最接近的参数是可变参数模板:

struct foo
{
    size_t a;
    size_t b;
    unsigned char c[32];

    template<typename ... UnsignedChar>
    constexpr foo(size_t a_, size_t b_, UnsignedChar ... s) : 
        a(a_), 
        b(b_), 
        c{s...} //use curly braces here
    { 
    }
};

And then use it as: 然后将其用作:

foo f(10, 20, 1,2,3,4,5, .....,32);
     //a,  b, -------s-----------

Note that if you pass less than 32 values for the third argument s , the rest of the elements of c will be initialized with 0 , and if you pass more than 32 values, the compiler (I guess) will give warning (or error!). 请注意,如果为第三个参数s传递的值少于32个,则c的其余元素将以0初始化,如果传递的值大于32个,则编译器(我想)将给出警告(或错误!)。 )。

Or use std::array<unsigned char, 32> instead of unsigned char[32] . 或使用std::array<unsigned char, 32>代替unsigned char[32]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM