Does structured binding work with std::vector?

前端 未结 3 865
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 03:40

Is it possible to use structured binding with vectors?

E.g.

std::vector vec{1, 2, 3};
auto [a, b, c] = vec;

Above code u

3条回答
  •  执笔经年
    2020-12-15 03:55

    It's easy enough to create a basic wrapper over your vector that gives access to it like a tuple. Since there is indeed no way to retrieve a vector's size at compile time, this throws std::out_of_range if you attempt to destructure too short a vector. Unfortunately I don't know of a way to deduce the number of requested bindings, so that's explicit.

    Full code:

    #include 
    #include 
    #include 
    
    template 
    struct vector_binder {
        std::vector &vec;
    
        template 
        T &get() {
            return vec.at(I);
        }
    };
    
    namespace std {
        template
        struct tuple_size>
        : std::integral_constant { };
    
        template
        struct tuple_element> { using type = T; };
    }
    
    template 
    auto dissect(std::vector &vec) {
        return vector_binder{vec};
    }
    
    int main() {
        std::vector v{1, 2, 3};
        auto [a, b] = dissect<2>(v);
    
        a = 5;
        std::cout << v[0] << '\n'; // Has changed v through a as expected.
    }
    

    Rvalue and const versions of vector_binder as well as better names are left as an exercise to the reader :)

    See it live on Coliru

提交回复
热议问题