如何使用自定义值初始化模板类中的数组

How to initialize an array in a template class with a custom value?

本文关键字:数组 何使用 自定义 初始化      更新时间:2023-10-16

例如

template<size_t N>
class A
{
    array<int, N> m;
    static A const UNIT {1, 1, ...}; // repeated N times, 
                                     // but I can't because of currently unspecified N
}

如何使用自定义值1初始化模板大小的数组?

您可以使用填充函数。这也适用于静态常量成员。

template<size_t N>
class A {
    array<int, N> m;
    public:
    static A const unit;
    A() { m.fill(1); }
};
template<size_t N>
A<N> const A<N>::unit{};