2

What type should I use to it compile for s parameter in the constructor? I tried unsigned char s[32] and unsigned char *s but both give compiler error:

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)
    { 
    }

}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
The Mask
  • 17,007
  • 37
  • 111
  • 185

1 Answers1

4

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!).

Or use std::array<unsigned char, 32> instead of unsigned char[32].

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 1
    @0x499602D2: `struct array { unsigned char data[32]; };` would work in C++03. That is, wrap the array in a struct, or create your own array container just like `std::array`. – Nawaz Apr 13 '14 at 17:32
  • 1
    Yeah, remember there's `boost::array`. – chris Apr 13 '14 at 17:35
  • what compiler are you using and is there nonstandard C++ in your code? I get a lot of error on clang++ 3.3: `error: non-constant-expression cannot be narrowed from type 'char' to 'unsigned char' in initializer list [-Wc++11-narrowing] c{s...}` one error for each `s`' argument. – The Mask Apr 13 '14 at 17:42
  • I figured it out: s isn't compatible to C: `char` and `unsigned char`. I need to keep `c` as `unsigned`. can I do it work? – The Mask Apr 13 '14 at 17:47
  • And `f(10, 20, 1)` doesn't work because argument #3 isn't `char` but `int` and it result into compiler error – The Mask Apr 13 '14 at 17:48
  • 1
    @TheMask: Instead of `c{s...}`, write `c{static_cast(s)...}`. That should work. – Nawaz Apr 13 '14 at 17:49
  • 1
    Thanks. I thought it but I didn't knew it could work to an array. Some C++ stuff are still confusing to me. I come from C... – The Mask Apr 13 '14 at 17:51
  • Your solution is so amazing I ended up without use a single macro or complex templates to do my implementation. Thanks very very much! – The Mask Apr 13 '14 at 18:27