Warum hat C++ keine Tuples?



  • a,b = foo(1)
    

    Sowas wie in Python wäre doch cool.



  • std::pair<T, U> p = foo(1);
    
    p.first // a
    p.second // b
    // oder
    std::tr1::tuple<T, U, V, W> t = foo(1);
    
    std::tr1::get<0>(t) // a
    // ...
    

    oder wenn man die Schreibweise anders haben will, kann man sich auch helfen.

    template<typename T, typename U>
    struct pair_binder_ {
      T &a;
      U &b;
    
      pair_binder_(T &a, U &b) : a(a), b(b) { }
      pair_binder_(pair_binder &p) : a(p.a), b(p.b) { }
    
      pair_binder_ &operator=(std::pair<T, U> &p) {
        a = p.first;
        b = p.second;
        return *this;
      }
    };
    
    template<typename T, typename U>
    pair_binder_<T, U> pair_bind(T &a, U &b) { return pair_binder(a, b); }
    
    // ...
    pair_bind(a, b) = foo(1);
    


  • Ist aber ganz schön umständlich. Und tuple != pair.

    a,b,c = foo2()
    

    geht auch



  • schreiben schrieb:

    Ist aber ganz schön umständlich. Und tuple != pair.

    a,b,c = foo2()
    

    geht auch

    std::tr1::tuple

    pair_bind finde ich jetzt nicht viel umständlicher (bzw. tuple bind als Erweiterung).


Anmelden zum Antworten