decltype Frage



  • Bei

    struct s {
        std::vector<int> foo;
    };
    std::vector<s>::const_iterator iter;
    

    ist decltype(iter->foo) ein std::vector<int> . Bei decltype((iter->foo)) (man beachte die doppelte Klammer) kommt const std::vector<int>& heraus.

    Kann mir das jemand erklären? Inwiefern und wieso spielt die Klammerung da eine Rolle?



  • hehe^^

    mir altem spätchecker stellt sich erstmal die frage was decltype überhaupt macht?!?! xD

    einen typ definieren? bzw deklarieren?



  • Das ist beabsichtigtes Verhalten. Beispiel:

    int a;
    

    Was soll nun decltype(a) sein? Die erste Antwort ist natürlich int . Eine mögliche Antwort kann aber auch int& sein. Für beides gibt es Anwendungsfälle. Deshalb:

    decltype(a); // int, denn a ist eine Variable vom Typ int
    decltype((a)); // int&, denn (a) ist ein Ausdruck vom Typ int&, keine Variable
    

    Das findet man aber so ziemlich überall, wo decltype erklärt wird.



  • Das macht Sinn, danke schön!



  • Skym0sh0 schrieb:

    mir altem spätchecker stellt sich erstmal die frage was decltype überhaupt macht?!?! xD

    einen typ definieren? bzw deklarieren?

    decltype gibt dir einen Typ zurück, ziemlich praktisch das Ganze:

    template<typename t, typename u>
    decltype(t()+u()) add( const t& T, const u& U ) {
        return T + U;
    }
    

    Das decltype gibt hier den Typ an, der bei der Addition herauskommt.

    Brauchen tut man das Ganze wohl eher bei Template Meta Programming und Bibliothekskram, im eigentlichen Anwendercode wahrscheinlich eher selten.



  • Siehe auch hier, Abschnitt 3.2.



  • ipsec schrieb:

    decltype((a)); // int&, denn (a) ist ein Ausdruck vom Typ int&

    n3225.pdf, 5/5

    If an expression initially has the type "reference to T" the type is adjusted to T prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.

    n3225,pdf, 7.1.6.2/4:

    The type denoted by decltype(e) is defined as follows

    • if e is an unparenthesized id-expression or a class member access (5.2.5), decltype(e) is the type of the entity named by e. If there is no such entity, or if e names a set of overloaded functions, the program is ill-formed;
    • otherwise, if e is a function call (5.2.2) or an invocation of an overloaded operator (parentheses around e are ignored), decltype(e) is the return type of the statically chosen function;
    • otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;
    • otherwise, decltype(e) is the type of e.

    Nachdem, was ich da zitiert habe, würde ich eher sagen, dass (a) ein Lvalue-Ausdruck vom Typ int ist und dass der dritte Unterpunkt mit T=int zutrifft.

    kk


Log in to reply