Search code examples
c++gccc++11variadic-templates

variadic template of a specific type


I want a variadic template that simply accepts unsigned integers. However, I couldn't get the following to work.

struct Array
{
    template <typename... Sizes> // this works
    // template <unsigned... Sizes> -- this does not work (GCC 4.7.2)
    Array(Sizes... sizes)
    {
        // This causes narrowing conversion warning if signed int is supplied.
        unsigned args[] = { sizes... };
        // ...snipped...
    }
};

int main()
{
    Array arr(1, 1);
}

Any help appreciated.

EDIT: In case you're wondering, I'm trying to use variadic template to replicate the following.

struct Array
{
    Array(unsigned size1) { ... }
    Array(unsigned size1, unsigned size2) { ... }
    Array(unsigned size1, unsigned size2, unsigned size3) { ... }
    // ...
    Array(unsigned size1, unsigned size2, ..., unsigned sizeN) { ... }
};

Solution

  • I'm not sure why you expected that to work. Clang tells me the error is unknown type name 'Sizes' in the declaration of the constructor. Which is to be expected, since Sizes isn't a type (or rather, a template pack of types), it's a template pack of values.

    It's unclear what exactly you're trying to do here. If you pass integral values in as template parameters, what are the constructor parameters supposed to be?


    Update: With your new code all you need is a static_cast<unsigned>().

    struct Array
    {
        template <typename... Sizes> // this works
        Array(Sizes... sizes)
        {
            unsigned args[] = { static_cast<unsigned>(sizes)... };
            // ...snipped...
        }
    };