的std :: initializer_list作为的std ::数组构造 [英] std::initializer_list as std::array constructor

查看:360
本文介绍了的std :: initializer_list作为的std ::数组构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要传递参数的包装类,看起来像这样的小例子:

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 };           
    }
};

我试图与initializer_list大小初始化数组但没有任何工程(评论源的部分)只有不断{} 5,2,3,4,5,6,7,8,9,10部分确实

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?

真诚
Matyro

Sincerely Matyro

编辑1:主要的问题是,TStack确实(在大多数情况下)没有一个默认的构造函数,所以我需要初始化施工阵列

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

推荐答案

通过的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

使用的std ::阵列

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

这篇关于的std :: initializer_list作为的std ::数组构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆