Function Templates vs. Auto Keyword

前端 未结 3 2125
抹茶落季
抹茶落季 2021-01-31 17:15

Can the auto keyword in C++11 replace function templates and specializations? If yes, what are the advantages of using template functions and specializations over

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-31 17:51

    In a nutshell, auto cannot be used in an effort to omit the actual types of function arguments, so stick with function templates and/or overloads. auto is legally used to automatically deduce the types of variables:

    auto i=5;
    

    Be very careful to understand the difference between the following, however:

    auto x=...
    auto &x=...
    const auto &x=...
    auto *px=...; // vs auto px=... (They are equivalent assuming what is being 
                  //                 assigned can be deduced to an actual pointer.)
    // etc...
    

    It is also used for suffix return types:

    template 
    auto sum(const T &t, const U &u) -> decltype(t+u)
    {
      return t+u;
    }
    

提交回复
热议问题