How is std::tuple implemented?

前端 未结 4 477
臣服心动
臣服心动 2021-01-31 16:03

I\'d like to know how are tuple implemented in standard library for C++0x. I tried to read description in libstdc++ manual and then read template listing, but it\'s really hard

4条回答
  •  鱼传尺愫
    2021-01-31 17:03

    I thought I would add a non-pseudocode simple recursive implementation for reference

    #include 
    
    // Contains the actual value for one item in the tuple. The 
    // template parameter `i` allows the
    // `Get` function to find the value in O(1) time
    template
    struct TupleLeaf {
        Item value;
    };
    
    // TupleImpl is a proxy for the final class that has an extra 
    // template parameter `i`.
    template
    struct TupleImpl;
    
    // Base case: empty tuple
    template
    struct TupleImpl{};
    
    // Recursive specialization
    template
    struct TupleImpl :
        public TupleLeaf, // This adds a `value` member of type HeadItem
        public TupleImpl // This recurses
        {};
    
    // Obtain a reference to i-th item in a tuple
    template
    HeadItem& Get(TupleImpl& tuple) {
        // Fully qualified name for the member, to find the right one 
        // (they are all called `value`).
        return tuple.TupleLeaf::value;
    }
    
    // Templated alias to avoid having to specify `i = 0`
    template
    using Tuple = TupleImpl<0, Items...>;
    
    int main(int argc, char** argv) {
        Tuple tuple;
        Get<0>(tuple) = 5;
        Get<1>(tuple) = 8.3;
        Get<2>(tuple) = "Foo";
        std::cout << Get<0>(tuple) << std::endl;
        std::cout << Get<1>(tuple) << std::endl;
        std::cout << Get<2>(tuple) << std::endl;
        return 0;
    }
    

提交回复
热议问题