C++Guns – RoboBlog

16.02.2022

C++ Guns: Play with std::tuple and std::apply

Filed under: Allgemein — Tags: — Thomas @ 11:02

Part 1: print std::array with std::integer_sequence
Part 2: convert tuple to parameter pack
Part 3: print std::array with std::apply and fold
Part 4: fold over std::tuple und erzeugten Assembler Code
Part 5: fold over std::tuple of std::vector of Types ...
Part 6: apply generic lambda to tuple
Part 7: Play with std::tuple and std::apply

#include <tuple>
#include <string_view>
#include <iostream>

void print(int i, std::string_view str, double x) {
    std::cout << i << " " << str << " " << x << "\n";
}



int main() {
    std::tuple tp {1, "abc", 3.1};

    // Ein Tuple in seine Einzelteile zerlegten durch eine Funktion die genau
    // die Tuple Elemente als Parameter hat
    std::apply(print, tp);


    // Ein Tuple in sein erstes Element und den Rest zerlergen.
    // Der Rest ist ne variadic argument list
    // Die Funktion print2 ist absichtlich ein Lambda, 
    // da das sonst mit dem auto Argument Typ nicht funktioniert. 
    // Will man print2 als freie Funktion haben, muss man sie als template schreiben.
    auto print2 = [](const int i, const auto&... restArgs) {
        std::cout << i << " Anzahl Restargumente: " << sizeof...(restArgs) << "\n";
    };
    std::apply(print2, tp);
}

1 abc 3.1
1 Anzahl Restargumente: 2

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress