如何实现std :: tuple? [英] How is std::tuple implemented?

查看:312
本文介绍了如何实现std :: tuple?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在C ++ 0x的标准库中实现元组。我尝试阅读 libstdc ++手册中的说明,然后阅读模板列表,但是很难理解它是如何工作的,尤其是在阅读代码时。

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 to understand how it works, especially when reading code.

有人可以用几句话解释我的元组实现的想法吗?我想知道这一点,因为我想在我的代码中使用元组,我想了解它是如何工作和它带来了什么类型的开销(仅扩展编译时间,对内存执行许多复制操作,执行许多其他功能的构造函数,等)。

Can someone explain me in few sentences the idea of tuple implementation? I want to know this, because I thinking about using tuples in my code and i want to understand how it works and what type of overhead does it brings (extends compile time only, perform many copy operations on memory, execute many other function in constructor, etc.).

推荐答案

实现元组的一种方法是使用多继承。元组元素由叶类保存,元组类本身从多个叶子继承。在伪代码中:

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<typename T0, typename T1, ..., typename Tn>
class PseudoTuple : TupleLeaf<0, T0>, TupleLeaf<1, T1>, ..., TupleLeaf<n, Tn> {
   ...
};

每个叶都有一个索引,所以每个基类都是唯一的,即使它们包含的类型相同,因此我们可以使用简单的static_cast访问 nth 元素:

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<TupleLeaf<0, T0>*>(this);
// ...
static_cast<TupleLeaf<n, Tn>*>(this);



我已经在这里写了关于这个flat元组实现的详细解释: C++11元组实现细节(第1部分)

这篇关于如何实现std :: tuple?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆