在C ++ 11函数中使用尾随返回类型的优势 [英] Advantage of using trailing return type in C++11 functions

查看:715
本文介绍了在C ++ 11函数中使用尾随返回类型的优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与常规返回类型相比,在C ++ 11中指定尾随返回类型有什么好处?在这里查看foo1foo2:

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();
}

推荐答案

在此示例中,它们的含义完全相同.

In this example, they mean the exact same thing.

但是,始终使用尾随返回类型表单有一些好处(Phil Nash称这些,因为返回类型在东端).

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. 使用参数.显然,在使用参数确定返回类型时,必须使用尾随返回类型.

template <typename T>
auto print(T const& t) -> decltype(std::cout << t) { return std::cout << t; }

  • 名称查找.在尾随返回类型中,名称查找包括成员函数定义的类范围.这意味着如果您想返回嵌套的类,则不必重新输入类:

  • 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
    

  • 同样,用于定义成员函数,在这些成员函数中,必须出于某种原因将类名明确地包含在全局名称空间中,并且返回类型是一个类:

  • 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.

    此外,从数学上讲,我们习惯于将函数视为A -> B而不是B(A),因此auto(*)(A) -> B作为接受A并返回B的函数指针更加接近到B(*)(A)的视图.

    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).

    另一方面,编写auto main() -> int看起来很荒谬.

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

    最终,这纯粹是基于观点的.只需编写有效的代码即可.

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

    这篇关于在C ++ 11函数中使用尾随返回类型的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆