Element-wise tuple addition

前端 未结 4 779
后悔当初
后悔当初 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:34

    The solution by @lubgr is satisfactory for your specific use-case. I offer you a generic solution which will work for tuples of different types, as well tuples of different (equal) sizes.

    #include 
    #include 
    #include 
    
    template
    constexpr auto add(const std::tuple& t1, const std::tuple& t2, 
                       std::index_sequence)
    {
        return std::tuple{ std::get(t1) + std::get(t2)... };
    }
    
    template
    constexpr auto operator+(const std::tuple& t1, const std::tuple& t2)
    {
        // make sure both tuples have the same size
        static_assert(sizeof...(T1) == sizeof...(T2));
    
        return add(t1, t2, std::make_index_sequence{});
    }
    

    I used a few C++17 features (mainly template-related) without which the code would become a bit more complicated. A possible improvement would be to make use of move-semantics.

    Obviously, this applies for the first "possible syntax" you provided.

提交回复
热议问题