How is std::tuple implemented?

前端 未结 4 533
臣服心动
臣服心动 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 16:54

    One approach to implementing tuples is using multiple-inheritance. The tuple-elements are held by leaf-classes, and the tuple class itself inherits from multiple leafs. In pseudo-code:

    template
    class PseudoTuple : TupleLeaf<0, T0>, TupleLeaf<1, T1>, ..., TupleLeaf {
       ...
    };
    

    Each leaf has an index, so that each base-class becomes unique even if the types they contain are identical, so we can access the nth element with a simple static_cast:

    static_cast*>(this);
    // ...
    static_cast*>(this);
    

    I've written up a detailed explanation about this "flat" tuple implementation here: C++11 tuple implementation details (Part 1)

提交回复
热议问题