Can i use auto or decltype instead trailing return type?

前端 未结 1 1845
礼貌的吻别
礼貌的吻别 2021-02-06 19:23

I find trailing return type so easy to define the return of a function that returns a complicated types e.g:

auto get_diag(int(&ar)[3][3])->i         


        
1条回答
  •  [愿得一人]
    2021-02-06 20:12

    auto& get_diag2(int(&ar)[3][3]){ // adding & auto because otherwise it converts the array to pointer
        static int diag[3]{
            ar[0][0], ar[1][1], ar[2][2]
        };
        return diag;
    }
    

    Will not work in a C++11 compiler. Using auto without a trailing return type was added to C++14 and acts like how auto works when using it for a variable. This means it will never return a reference type so you have to use auto& to return a reference to the thing you want to return.

    If you do not know if you should return a reference or a value (this happens a lot in generic programming) then you can use decltyp(auto) as the return type. For example

    template
    decltype(auto) Example(F func, Args&&... args) 
    { 
        return func(std::forward(args)...); 
    }
    

    will return by value if func returns by value and return by reference if func returns a reference.


    In short if you are using C++11 you have to specify the return type, either in front or as a trailing return type. In C++14 and above you can just use auto/decltype(auto) and let the compiler deal with it for you.

    0 讨论(0)
提交回复
热议问题