Advantage of using trailing return type in C++11 functions

我怕爱的太早我们不能终老 提交于 2019-12-21 10:21:12

问题


What is the advantage of specifying a trailing return type in C++11, as opposed to a normal return type? Look at foo1 vs foo2 here:

int foo1() {
    return 1;    
}

auto foo2() -> int {
    return 1;    
}

int main() {
    foo1();
    foo2();
}

回答1:


In this example, they mean the exact same thing.

However, there are a few advantages to using the trailing return type form consistently (Phil Nash calls these "East End Functions", since the return type is on the east end).

  1. Using parameters. Obviously when using parameters to determine the return type, you must use a trailing return type.

    template <typename T>
    auto print(T const& t) -> decltype(std::cout << t) { return std::cout << t; }
    
  2. Name lookup. In a trailing return type, name lookup includes the class scope for member function definitions. This means you don't have to retype the class if you want to return a nested class:

    Type C::foo() { ... }         // error: don't know what Type is
    C::Type C::foo() { ... }      // ok
    
    auto C::foo() -> Type { ... } // ok
    
  3. Likewise, for defining member functions where the class name for some reason must be disambiguated to be in the global namespace and the return type is a class:

    D ::C::foo() { ... }         // error, parsed as D::C::foo() { ... }
    
    auto ::C::foo() -> D { ... } // ok
    

There are cases where trailing-return-type is mandatory, there are cases where it is helpful, and there are cases where it does the same thing. There are not cases where it is worse for reasons other than simply character count.

Plus, mathemtically we're used to thinking of functions as A -> B and not so much B(A), and so auto(*)(A) -> B as a function pointer taking an A and returning a B is a little closer to that view than B(*)(A).


On the other hand, writing auto main() -> int looks ridiculous.


Ultimately, this is purely opinion based. Just write code that works.



来源:https://stackoverflow.com/questions/52103775/advantage-of-using-trailing-return-type-in-c11-functions

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