Search code examples
c++constructorconstantsvariadic

Initialize const array in a variadic constructor


I want to initialize a const array from variadic parameters. But with this code only the first value in the values arrays is initialized, the rest are zeroes. How can I fix it?

I never dealt with variadic parameters and I don't know how do they basically work.

struct Object
{
    const int values[8];

    constexpr Object()
        : values{}
    {}

    constexpr Object(int values...)
        : values{values}
    {}
}

// in main.cpp :
Object o = { 1, 2, 3 };

Additional question: can I write a class template and make its array size to be equal to variadic parameters count?


Solution

  • Since C++17 we can take advantage of user-defined deduction guides:

    template <class T, size_t N>
    class Object
    {
        T d_[N];
    public:
        Object() = default;
    
        template <class... Ts>
        constexpr Object(Ts... others) : d_{others...} {}
    
        constexpr auto size() const noexcept { return N; }
    
        constexpr auto operator[] (size_t i) const noexcept { return d_[i]; }
    };
    
    // Deduction guide
    template <class T, class... Ts> Object(T, Ts...) -> Object<T, 1 + sizeof...(Ts)>;
    

    Live, here.