Can i use auto or decltype instead trailing return type?

帅比萌擦擦* 提交于 2019-12-03 04:42:54
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<class F, class... Args>
decltype(auto) Example(F func, Args&&... args) 
{ 
    return func(std::forward<Args>(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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!