std::initializer_list as std::array constructor

2019-05-20 08:03发布

I need to pass arguments to a wrapper class that looks as minimal example like this:

template<class TStack, unsigned int TBins>
class Wrapper : Stack<......>
{
    std::array<TStack, TBins> m_oStacks;

    template<typename ... Args>
    Wrapper(std::initializer_list<const unsigned int> const& size, Args&&... args)
    : Stack<.......>(args), m_oStacks{5,2,3,4,5,6,7,8,9,10}
    //, m_oStacks(size) //,m_oStacks{size} //,m_oStacks{{size}}
    {
        //m_oStacks = { size };           
    }
};

I tried to init the array with the initializer_list size but nothing works (commented parts of the source) only the constant {5,2,3,4,5,6,7,8,9,10} part does

Someone know the reason and a fix?

Sincerely Matyro

Edit 1: The main problem is that TStack does (in most cases) not have a default constructor so i need to initialize the array at construction

1条回答
何必那么认真
2楼-- · 2019-05-20 08:46

With std::initializer_list:

template <typename TStack, std::size_t TBins>
class Wrapper
{
public:
    Wrapper(std::initializer_list<unsigned int> il)
        : Wrapper(il, std::make_index_sequence<TBins>{})
    {
    }

private:
    template <std::size_t... Is>
    Wrapper(std::initializer_list<unsigned int> il, std::index_sequence<Is...>)
        : m_oStacks{{ *(il.begin() + Is)... }}
    {
    }

    std::array<TStack, TBins> m_oStacks;
};

DEMO

With std::array:

template <typename TStack, std::size_t TBins>
class Wrapper
{
public:
    Wrapper(const std::array<unsigned int, TBins>& a)
        : Wrapper(a, std::make_index_sequence<TBins>{})
    {
    }

private:
    template <std::size_t... Is>
    Wrapper(const std::array<unsigned int, TBins>& a, std::index_sequence<Is...>)
        : m_oStacks{{ a[Is]... }}
    {
    }

    std::array<TStack, TBins> m_oStacks;
};

DEMO 2

查看更多
登录 后发表回答