C ++初始化构造器初始值设定项列表中的模板数组

时间:2020-05-16 14:32:43

标签: c++ templates

我有一个没有默认构造函数的组件类,而是需要一个对象传递给它。我希望有一个模板类,该模板类可构建堆栈空间,此组件的任意大小的数组。因为它没有,并且实际上不应该具有默认构造函数,所以我遇到了使它起作用的问题。关于模板类的另一个说明是,它只能有一个参数传递给它,并且它必须使用它来初始化数组的所有元素。

我要为其创建数组的组件的相关部分。

class CSomeComponent : public CComponent {
public:
    CSomeComponent(const IObject* pObject) : CComponent(pObject) {
    }
};

我要工作的模板数组的相关部分。

template<size_t _Count>
class CComponentArray {
public:
    CComponentArray(const IObject* pObject) : m_component(...) {
    }

private:
    CSomeComponent m_component[_Count];
};

我不能改变组件没有默认构造函数的事实。我也不能给组件数组模板提供多个参数。这两个限制是为什么我不知道该怎么做的原因,因此希望其他人也可以。谢谢!

1 个答案:

答案 0 :(得分:1)

使用std::array,然后可以创建一个constexpr函数来初始化并返回数组:

namespace details
{
template <class T, std::size_t Size, class... Args, std::size_t... I>
constexpr auto make_arr_emplace_impl(std::index_sequence<I...>, Args&&... args)
    -> std::array<T, Size>
{
    return std::array<T, Size> {(I, T{args...})...};
}
}


/* creates an std::array<T, Size> where each element is created by calling `T{args...}`
 * note: args will not be moved
 * forwarding references used for preserving constness and binding to temporaries
*/
template <class T, std::size_t Size, class... Args>
constexpr auto make_arr_emplace(Args&&... args) -> std::array<T, Size>
{
    return details::make_arr_emplace_impl<T, Size>(std::make_index_sequence<Size>{}, args...);
}
template<size_t Count>
class CComponentArray {
public:
    CComponentArray(const IObject* pObject)
        : m_component{make_arr_emplace<CSomeComponent, Count>(pObject)}
    {
    }

private:
    std::array<CSomeComponent, Count> m_component;
};

请注意,以双下划线或一个下划线和大写字母开头的标识符(例如您的_Count)保留用于实现。