c++ - std::initializer_list 作为 std::array 构造函数

标签 c++ arrays c++11 initializer-list

我需要将参数传递给一个包装类,它看起来像这样的最小示例:

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} 部分可以

有人知道原因和解决方法吗?

真诚的 马蒂罗

编辑1:主要问题是TStack(在大多数情况下)没有默认构造函数,因此我需要在构造时初始化数组

最佳答案

使用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::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

关于c++ - std::initializer_list 作为 std::array 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35488730/

相关文章:

java - 在Java中是否有 "right "方法将字符串和整数存储在同一个数组中?

multithreading - C++0x : thread, gcc 还是我的错误?

c++ - 继承的构造函数和 "explicit is better than implicit"

c++ - 使用 fork() 的子进程和父进程

c++ - 类成员函数的函数模板特化

c++ - C/C++ 确定程序运行的驱动器

javascript - 数组被插入另一个数组时不显示

php - 为 PHP 数组分配索引

c++ - 为什么复制和 move 构造函数以相同数量的 memcopies 结束?

c++ - 添加按钮到 QVideoWidget