2

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

3
  • @Matyro Class std::array does not have a constructor that accepts the initializer_list. You should copy initializer_list in the array yourself. Commented Feb 18, 2016 at 17:51
  • 1
    Use std::array<TStack, TBins> instead of std::initializer_list<const unsigned int>, it can be list-initialized as well, and a std::array itself does have a copy constructor Commented Feb 18, 2016 at 18:16
  • That solution works fine, thx Commented Feb 18, 2016 at 18:56

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

I din't think that through all the way. Looks great.
The first case results in UB if the length of il is smaller than TBINS.
Now can you deduce the TBins size (in either case)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.