Element-wise tuple addition

前端 未结 4 784
后悔当初
后悔当初 2021-02-06 23:29

I have some values held in a tuple, and I am looking to add another tuple to it element-wise. So I would like functionality like this:

std::tuple         


        
4条回答
  •  情深已故
    2021-02-06 23:54

    You could use something like this, which supports all three of your syntax proposals:

    #include 
    #include 
    
    namespace internal
    {
        //see: https://stackoverflow.com/a/16387374/4181011
        template
        void add_rhs_to_lhs(T& t1, const T& t2, std::integer_sequence)
        {
            auto l = { (std::get(t1) += std::get(t2), 0)... };
            (void)l; // prevent unused warning
        }
    }
    
    template 
    std::tuple& operator += (std::tuple& lhs, const std::tuple& rhs)
    {
        internal::add_rhs_to_lhs(lhs, rhs, std::index_sequence_for{});
        return lhs;
    }
    
    template 
    std::tuple operator + (std::tuple lhs, const std::tuple& rhs)
    {
       return lhs += rhs;
    }
    

    Working example:

    http://coliru.stacked-crooked.com/a/27b8cf370d44d3d5

    http://coliru.stacked-crooked.com/a/ff24dae1c336b937


    I would still go with named structs in most cases. Tuples are seldom the correct choice.

提交回复
热议问题