如何初始化模板大小的数组

How to initialize a template sized array?

本文关键字:数组 初始化      更新时间:2023-10-16

我想初始化一个没有默认构造函数的模板大小的对象数组,如以下代码所示:

#include <array>
template<std::size_t N>
class Foo
{
    public:
        class Bar
        {
                Foo<N> & _super;
            public:
                Bar(Foo<N> *super) :
                    _super(*super)
                {
                }
        };
        std::array<Bar, N>  _array;
        Foo(void) :
            _array{{}} // We need {this, ...} N times
        {
        }
};

int main(void)
{
    Foo<3>  foo;
    (void)foo;
    return 0;
}

这是一种说:"我想要一个 N 个对象的数组,都使用相同的参数初始化"?我认为模板元编程有一种方法,但我不知道该怎么做。

make_index_sequence的帮助下,一切皆有可能:

   Foo() : Foo(std::make_index_sequence<N>()) {} 
   template <size_t... I> Foo(std::index_sequence<I...> ) : _array{((void)I, this)...} {}

请注意 _array 构造函数中的逗号运算符 (,) - 由 @Quentin 提供(与函数调用相反)。

你可以一次添加一个this,直到你得到N,此时你只需初始化_array

    Foo()
    : Foo(this)
    { }
private:
    template <class... T, std::enable_if_t<(sizeof...(T) < N), void*> = nullptr>
    Foo(T... args)
    : Foo(args..., this)
    { }
    template <class... T, std::enable_if_t<(sizeof...(T) == N), void*> = nullptr>
    Foo(T... args)
    : _array{{args...}}
    { }