c++ - c++ 中没有 std::tuple 的 std::iterator 有什么原因吗?

标签 c++ iterator tuples

std::tuple 有一个std::iterator 似乎很自然。但是它没有实现,所以程序员实现了自己的版本。例如,一个位于 Jonathan Müller's Blog。 .

我是否忽略了什么?有什么理由没有 tuple_iterator 的“官方版本”吗?

最佳答案

std::tuple 不是容器,至少在标准库容器的意义上不是。它不能用通常的方法迭代,因为它包含不同类型的对象。标准容器是同构容器,而 std::tuple 是异构容器。

这并不意味着你不能遍历一个元组,但它非常麻烦而且你不能使用既定的语法:

假设您想像遍历 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 的迭代器。访问下面的真实对象并不那么容易。而且这种迭代器在标准库中任何需要迭代器的地方都不能使用,至少在没有一些额外工作的情况下是这样。

还有一项关于元编程(反射、内省(introspection))的提案的工作,该提案具有(或具有、未遵循)以下语法:

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();
}

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

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++ - c++ 中没有 std::tuple 的 std::iterator 有什么原因吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61345033/

相关文章:

c++ - 通过外部评估调度将标准兼容性与不透明数据连接起来

c++ - 为什么 tuple_size 是特征而不是成员

python - 如何在 Python 中迭代元组的堆栈

c# - 在控制台应用程序中使用图像而不是文本

c++ - 如何将 for_each 与作为重载 operator() 的函数一起使用

c++ - QDialog 不会停留在父 QMainWindow 之上

c++ - 我可以在空范围内调用 <algorithm> 设施吗?

python - 在 python 中连接列表和元组的行为不一致

C++ 未定义对代码中实现和模板化的函数的引用

c++ - 根据其成员子对象之一的地址计算对象的地址