C++Guns – RoboBlog

13.06.2018

C++ Guns: fold over std::tuple of std::vector of Types ...

Filed under: Allgemein — Tags: — Thomas @ 16:06

Okay das ist ein seltsames Konstrukt. Wir haben viele Instanzen vieler Typen über die alle zusammen iteriert wird. Eigentlich ist der Code ziemlich klar. Ansonsten.... WOW was alles mit C++17 geht.

#include <type_traits>
#include <tuple>
#include <vector>
#include <iostream>

template<typename... Args>
struct A : std::tuple<std::vector<Args>...>
{   
    template<typename T>
    void add(const T&x) {
        std::get<std::vector<T>>(*this).push_back(x);
    }
};

namespace std {
    template<typename...Args>
    struct tuple_size<A<Args...>> : std::integral_constant<std::size_t, sizeof...(Args)> {};
}

auto func() {
    A<int,double> a;
    a.add(1);
    a.add(2);
    a.add(10.1);
    a.add(20.1);
    
    return a;
}

template<typename T>
std::ostream& operator<<(std::ostream& s, const std::vector<T>& vec) {
    for(const auto& x : vec) {
        s << x << ' ';
    }
    return s;
}

void func3() {
    auto a = func();
    std::apply([&](const auto&...vectors){ (std::cout << ... << vectors);  }, a);  
}

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress