【问题标题】:Initialize initializer_list from template parameters从模板参数初始化 initializer_list
【发布时间】:2018-09-28 10:43:31
【问题描述】:

我需要在查找库中设置大量的 std::vector。都有结构:

{N, N, ..., -N, -N}

我可以使用一些模板函数来做到这一点:

template<int N>
static constexpr std::initializer_list<int> H2 = {N, -N};
template<int N>
static constexpr std::initializer_list<int> H4 = {N, N, -N -N};
...

从中我可以简单地做到:

std::vector<int> v22 = H2<3>    
std::vector<int> v35 = H3<5>
etc.

但是有没有办法将数字 2、4 等也包含在模板参数中?

【问题讨论】:

    标签: c++11 templates template-meta-programming


    【解决方案1】:

    是的,可以通过使用std::integer_sequence 和变量模板特化来实现:

    template <typename, int N>
    static constexpr std::initializer_list<int> HImpl;
    
    template <int N, int... Is>
    static constexpr std::initializer_list<int> HImpl<std::index_sequence<Is...>, N>
        = {(Is < sizeof...(Is) / 2) ? N : -N...};
    
    template <int Count, int N>
    static constexpr auto H = HImpl<std::make_index_sequence<Count>, N>;
    

    用法:

    int main()
    {
        std::vector<int> v = H<10, 1>;
        for(int x : v) std::cout << x << ' ';
    }
    

    输出:

    1 1 1 1 1 -1 -1 -1 -1 -1 
    

    live example on wandbox.org

    【讨论】:

    • 谢谢,正是我需要的!
    猜你喜欢
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多