decltype vs auto

后端 未结 4 1895
自闭症患者
自闭症患者 2021-01-30 04:17

As I understand it, both decltype and auto will attempt to figure out what the type of something is.

If we define:

int foo () {         


        
4条回答
  •  清歌不尽
    2021-01-30 04:45

    auto (in the context where it infers a type) is limited to defining the type of a variable for which there is an initializer. decltype is a broader construct that, at the cost of extra information, will infer the type of an expression.

    In the cases where auto can be used, it is more concise than decltype, as you don't need to provide the expression from which the type will be inferred.

    auto x = foo();                           // more concise than `decltype(foo()) x`
    std::vector v{ foo() };  // cannot use `auto`
    

    The keyword auto is also used in a completely unrelated context, when using trailing return types for functions:

    auto foo() -> int;
    

    There auto is only a leader so that the compiler knows that this is a declaration with a trailing return type. While the example above can be trivially converted to old style, in generic programming it is useful:

    template 
    auto sum( T t, U u ) -> decltype(t+u)
    

    Note that in this case, auto cannot be used to define the return type.

提交回复
热议问题