简体   繁体   English

从 C++ 中的自定义异构容器打印

[英]Printing from a custom heterogeneous container in C++

I am reading a blog about building a custom heterogeneous container in C++.我正在阅读一篇关于在 C++ 中构建自定义异构容器的博客。 In the blog, the author used visitor pattern to print out each element of the container ordered by their types.在博客中,作者使用访问者模式打印出容器中按类型排序的每个元素。 I'm wondering if it is possible for me to write a visitor such that I could print out the elements in the order they were inserted?我想知道我是否可以写一个访问者,以便我可以按照插入的顺序打印出元素?

As you store element by type, you loose insertion order, so you have to change当您按类型存储元素时,您会丢失插入顺序,因此您必须更改

template<class T>
static std::unordered_map<const heterogeneous_container*, std::vector<T>> items;

by经过

template <class T>
static std::unordered_map<const heterogeneous_container*,
                          std::vector<std::pair<std::size_t, T>>> items;

Add a visit_ordered:添加一个visit_ordered:

template <typename T, class V>
void visit_with_index_impl_help(V& visitor)
{
    for (auto&& p : items<T>[this])
    {
        visitor(p.first, p.second);
    }
}
template <class V, typename... Ts>
void visit_ordered_impl(V& visitor, type_list<Ts...>)
{
    std::vector<std::pair<std::size_t, std::function<void()>> funcs;
    const auto inserter = [&](std::size_t i, auto&& elem) {
        funcs.emplace_back(i, visitor(elem));
    };

    (..., visit_with_index_impl_help<Ts>(inserter));
    const auto less_by_first = [](const auto& lhs, const auto& rhs){ return lhs.first < rhs.first; };
    std::sort(funcs.begin(), funcs.end(), less_by_first);
    for (auto&& func : funcs) {
        func();
    }
}

template <class V>
void visit_ordered(V& visitor)
{
    visit_ordered_impl(visitor, typename std::decay_t<V>::types{})
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM