std::initializer_list as std::array constructor

僤鯓⒐⒋嵵緔 提交于 2019-12-22 18:07:18

问题


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:


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



来源:https://stackoverflow.com/questions/35488730/stdinitializer-list-as-stdarray-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!