【问题标题】:Initialize std array with numbers from 1-to N template argument使用从 1 到 N 模板参数的数字初始化 std 数组
【发布时间】:2019-10-28 18:20:00
【问题描述】:

我有一个模板类,想用参数中指定的从1N 的数字初始化它的std::array。如何做到这一点?

#include <iostream>
#include <array>

template<unsigned int N>
class Jollo
{
private:
    std::array<int,N> deck;
public:
    Jollo()
    {
        static_assert(N>1,"Jollo: deck size must be higher than '1'");
        deck = std::array<int,N>{1...N}; //how to do this? = {1,2,4,5,6,7,8,9,10,11,12,13,14,15}
    }

};

int main()
{
    Jollo<15> j;
    return 0;
}

【问题讨论】:

  • 编译时实例化(比你要求的多一点):stackoverflow.com/questions/37297359/…
  • 您可以使用std::iota,例如stackoverflow.com/questions/17694579/…(类似的问题,但带有向量)。
  • 离题,但您的static_assert 可能应该在类级别,而不是在构造函数中。
  • 它可以工作,但如果 static_assert 引用类模板参数,则将它们放在类级别更为惯用。如果构造函数是模板化的,这可能不起作用,例如,godbolt.org/z/DLP_Ew
  • 也是 SFINAE template&lt;size_t N, std::enable_if_t&lt; (N &gt; 1), int &gt; = 0&gt;。虽然报错信息不是很清楚。

标签: c++ arrays


【解决方案1】:

std::iota 是您要查找的内容:

Jollo()
{
    static_assert(N>1,"Jollo: deck size must be higher than '1'");
    std::iota(deck.begin(), deck.end(), 1); // fills array from 1 to N
}

如果需要 constexpr,我会进行循环,因为 iota 尚未标记为 constexpr:

constexpr Jollo()
{
    static_assert(N>1,"Jollo: deck size must be higher than '1'");
    for (int i = 0 ; i < N ; ++i) {
        deck[i] = i + 1;
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-07-15
  • 2016-10-23
  • 1970-01-01
  • 1970-01-01
  • 2021-03-26
  • 2019-06-24
  • 1970-01-01
  • 2012-04-11
相关资源
最近更新 更多