How to emulate C array initialization “int arr[] = { e1, e2, e3, … }” behaviour with std::array?

后端 未结 10 961
难免孤独
难免孤独 2020-11-22 17:23

(Note: This question is about not having to specify the number of elements and still allow nested types to be directly initialized.)
This question discu

10条回答
  •  被撕碎了的回忆
    2020-11-22 17:49

    (Solution by @dyp)

    Note: requires C++14 (std::index_sequence). Although one could implement std::index_sequence in C++11.

    #include 
    
    // ---
    
    #include 
    #include 
    
    template 
    using c_array = T[];
    
    template
    constexpr auto make_array(T (&&src)[N], std::index_sequence) {
        return std::array{{ std::move(src[Indices])... }};
    }
    
    template
    constexpr auto make_array(T (&&src)[N]) {
        return make_array(std::move(src), std::make_index_sequence{});
    }
    
    // ---
    
    struct Point { int x, y; };
    
    std::ostream& operator<< (std::ostream& os, const Point& p) {
        return os << "(" << p.x << "," << p.y << ")";
    }
    
    int main() {
        auto xs = make_array(c_array{{1,2}, {3,4}, {5,6}, {7,8}});
    
        for (auto&& x : xs) {
            std::cout << x << std::endl;
        }
    
        return 0;
    }
    

提交回复
热议问题