2

I would like to write a templated class constructor that accepts an initializer list in order to construct an internal std::array. I am having trouble achieving the syntax I would like. The code below describes my issue.

#include <array>

struct Element
{
    int a;
    int b;
};

// Foo1
template <std::size_t N>
class Foo1
{
public:
    Foo1(Element const (&arr)[N])
        : m_Data(arr)
    {
    }

private:
    std::array<Element, N> m_Data;
};

// Foo2
class Foo2
{
public:
    Foo2(const std::initializer_list<Element>& list)
    //: m_Data(list)
    {
    }

    // std::array<Element, N> m_Data;
};

// Foo3
template <std::size_t N>
class Foo3
{
public:
    Foo3(const std::initializer_list<Element>& list)
        : m_Data(list)
    {
    }

private:
    std::array<Element, N> m_Data;
};

// Uses of Foo
int main()
{
    // This is my goal - does not compile
    Foo1 f11 = {
        {1, 2},
        {3, 4},
    };

    // Works, but have to call constructor explicitly
    Foo1 f12({
        {1, 2},
        {3, 4},
    });

    // Works, but class is not template so cannot initialize array
    Foo2 f2 = {
        {1, 2},
        {3, 4},
    };

    // Works, but have to explicitly specify initializer list size
    Foo3<2> f3 = {
        {1, 2},
        {3, 4},
    };
}

Note that, while this is similiar to this thread, it is slightly different as I would like the specific syntax below for constructing a class, and not calling a function.

Is this possible?

Gary Allen
  • 1,218
  • 1
  • 13
  • 28
  • 2
    `std::initializer_list` parameter isn't `constexpr`, so you cannot use its `size()` to specify array size... Moreover `{..}` has no type, so I fear that your syntax is not possible. – Jarod42 Sep 02 '21 at 15:06

0 Answers0