【问题标题】:std::array aggregate initialization and template integral typesstd::array 聚合初始化和模板整数类型
【发布时间】:2016-03-26 18:41:08
【问题描述】:

std::arraydocumentation,我们发现可以如下初始化(使用聚合初始化):

struct S {
    S(): arr{0,1} { }
    std::array<int,2> arr;
};

反正这种情况就出现问题了:

template<int N>
struct S {
    S(): arr{/*??*/} { }
    std::array<int,N> arr;
};

如何在构造s 时初始化数组(例如,值从0N-1 或使用constexpred 函数来传递索引)?

【问题讨论】:

    标签: c++ c++11 stl aggregate-initialization


    【解决方案1】:

    看看std::iota 被大量利用的力量:

    template <int N>
    struct S {
        S() {
            std::iota(arr.begin(), arr.end(), 0);
        }
    
        std::array<int, N> arr;
    };
    

    虽然如果你真的想使用聚合初始化,总有std::integer_sequence(需要C++14,但在SO上有很多C++11解决方案):

    template <int N>
    struct S {
        S() : S(std::make_integer_sequence<int, N>{}) {}
    
        std::array<int, N> arr;
    private:
        template <int... Is>
        S(std::integer_sequence<int, Is...> )
            : arr{Is...}
        { }
    };
    

    【讨论】:

    • @LorahAttkins 正确。并将其设为私有,以便其他人无法以无效序列传递。
    • std::iotastd::arraystd::vector 一起使用时呢?不是说初始化两次向量吗?
    • @skypjack 您不能将std::iota 与向量数组一起使用,因为向量不可递增。
    • 啊哈哈...你是对的,对不起。夏天不原谅!! :-D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 2015-10-05
    • 2012-02-10
    相关资源
    最近更新 更多