有什么原因为什么C ++中的std :: tuple没有std :: iterator? [英] Is there any reason why there is no std::iterator for std::tuple in c++?

查看:80
本文介绍了有什么原因为什么C ++中的std :: tuple没有std :: iterator?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::tuple设置一个std::iterator似乎很自然.但是,由于尚未实现,因此程序员在此处实现了自己的版本.例如,可以在乔纳森·穆勒的博客中找到一个.

It seems natural to have an std::iterator for std::tuple. However it is not implemented, so programmers implement there own versions. One is for example found at Jonathan Müller's Blog.

我忽略了什么吗?有任何理由为什么tuple_iterator没有正式版本"?

Do I overlook something? Is there any reason why there is no "official version" for an tuple_iterator?

推荐答案

std::tuple不是容器,至少在标准库容器的意义上不是这样.它不能使用常规方法进行迭代,因为它包含不同类型的对象.标准容器是同质容器,而std::tuple是异类容器.

std::tuple is not a container, at least not in the sense of the standard library containers. It cannot be iterated with the usual methods because it holds objects of different types. Standard containers are homogenous containers, while std::tuple is a heterogeneous container.

这并不意味着您不能遍历一个元组,但这非常麻烦并且您不能使用已建立的语法:

This doesn't mean that you can't iterate over a tuple, but it's very cumbersome and you can't use the established syntax:

假设您要像在std::vector这样的容器上进行迭代一样,对元组进行迭代:

Let's imagine you want to iterate over a tuple the same way you iterate over a container like std::vector:

std::tuple<int, std::string, bool> t = {...};

for (auto it = t.begin(); it != t.end(); ++it)
{
    auto elem = *it; // this cannot work the same way as with containers
                     // because each element is of a different type
}

您可以做几件事.使用持有容器类型的std::variant的迭代器.访问下面的真实对象并不容易.而且这种迭代器在标准库中期望迭代器的其他任何地方都无法使用,至少没有一些额外的工作.

There are a couple of things you could do. Use an iterator who holds a std::variant with the types of the container. Accessing the true object underneath is not as easy. And also this kind of iterator wouldn't be usable anywhere else in the standard library where an iterator is expected, at least not without some extra work.

还有一项关于元编程(反思,自省)的提案的工作,该提案具有(或曾经遵循,未遵循)以下语法:

Also there is work on a proposal for metaprogramming (reflexion, introspection) that has (or had, hadn't followed it) the following syntax:

std::tuple<int, std::string, bool> t = {...};

// something like this (can't remember the syntax exactly):
for constexpr ... (auto elem : t)
{
    // only the common set of operations permitted with `elem`
    // e.g. this is valid
    std::cout << elem << std::endl;

    // this is invalid:
    //elem.size();
}

这实际上会在编译时展开,从而导致以下代码:

This would actually be unrolled at compile time resulting in the following code:

std::tuple<int, std::string, bool> t = {...};

{
    int elem = std::get<0>(t);
    std::cout << elem << std::endl;
}
{
    std::string elem = std::get<1>(t);
    std::cout << elem << std::endl;
}
{
    bool elem = std::get<2>(t);
    std::cout << elem << std::endl;
}

这篇关于有什么原因为什么C ++中的std :: tuple没有std :: iterator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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