使用从1到N的模板参数编号初始化std数组

问题描述 投票:0回答:1

我有一个模板类,并希望使用参数中指定的从std::array1的数字来初始化其N。怎么做?

#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;
}
c++ arrays
1个回答
2
投票

std::iota是您要寻找的:

std::iota

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

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
}
© www.soinside.com 2019 - 2024. All rights reserved.