Home > OS >  Deduce the array-sizes in a variadic template function
Deduce the array-sizes in a variadic template function

Time:01-11

I try to write a constexpr function that accepts a variable number of C-Strings. And I want to deduce all of the sizes (here: L0 and LL) of the passed arrays. Looks like a stupid error I make there, but trying to do so, I get an error:

error: parameter packs not expanded with '...':
  204 | constexpr auto generate(const char (&s0)[L0], const char (&ss)[LL] ...) {
template<size_t L0, size_t... LL>
constexpr auto generate(const char (&s0)[L0], const char (&ss)[LL] ...) {
    constexpr size_t ll = (LL   ...);
    std::integral_constant<size_t, L0>::_;
    std::integral_constant<size_t, ll>::_;
        
    std::array<char, 1   L0   ll> r;
    return r;        
}

constexpr auto STR_X = generate("abc", "def");

This is done with gcc version 12.0 and -std=c 20.

CodePudding user response:

The problem should be the expansion of ss (that is variadic too)

// ellipsis here ...........................................VVV
constexpr auto generate(const char (&s0)[L0], const char (& ... ss)[LL]) {

CodePudding user response:

The problem is that you're using the ellipsis ... at the wrong place. The correction is shown below:

template<size_t L0, size_t... LL>
constexpr auto generate(const char (&s0)[L0], const char (&...ss)[LL]) {
                                                         //^^^
    
         
}

CodePudding user response:

You can make the function simpler by avoiding over-specification of the parameter type. Furthermore, since the first parameter isn't treated differently from the rest, it seems unnecessary:

constexpr auto
generate(auto&&... ss) {
    constexpr size_t ll = (sizeof(ss)   ...);
    return std::array<char, 1   ll>{};
}
  •  Tags:  
  • Related