简体   繁体   English

C++ 在构造函数初始化列表中初始化模板数组

[英]C++ Initializing a template array in a contructor initializer list

I have a component class that doesn't have a default constructor and needs an object passed to it instead.我有一个组件 class,它没有默认构造函数,需要传递给它的 object。 I want to have a template class that builds a stack space, arbitrarily sized array of this component.我想要一个模板 class 来构建堆栈空间,这个组件的任意大小的数组。 Because it doesn't and really shouldn't have a default constructor, I'm running into issues making it work.因为它没有而且真的不应该有默认构造函数,所以我遇到了让它工作的问题。 Another note on the template class is that it can only have one parameter passed to it, and it must use it to initialize all of the array's elements.另一个关于模板 class 的注意事项是它只能有一个参数传递给它,并且必须使用它来初始化数组的所有元素。

Relevant parts of the component I want to create the array of.我要创建数组的组件的相关部分。

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

Relevant parts of the template array I'm trying to make work.我正在尝试工作的模板数组的相关部分。

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

private:
    CSomeComponent m_component[_Count];
};

I can't change the fact that components don't have a default constructor.我无法改变组件没有默认构造函数的事实。 I also can't give the component array template more than one parameter.我也不能给组件数组模板一个以上的参数。 These two constraints are why I can't figure out how I'd do this, so hopefully someone else can.这两个限制是我无法弄清楚如何做到这一点的原因,所以希望其他人可以。 Thank you!谢谢!

Use std::array and then you can make a constexpr function that initializes and returns the array:使用std::array然后你可以创建一个 constexpr function 来初始化并返回数组:

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

Please note that identifiers starting with double underscore or one underscore and a capital letter - like your _Count - are reserved for implementation.请注意,以双下划线或一个下划线和一个大写字母开头的标识符(如您的_Count )保留用于实施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM