应该返回类型的语法样式是否为新的C ++ 11程序的默认值? [英] Should the trailing return type syntax style become the default for new C++11 programs?

查看:230
本文介绍了应该返回类型的语法样式是否为新的C ++ 11程序的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11支持一种新的函数语法:

C++11 supports a new function syntax:

auto func_name(int x, int y) -> int;

目前此函数将声明为:

int func_name(int x, int y);

新风格似乎还没有广泛采用(比如在gcc stl中)

The new style does not seem to be widely adopted yet (say in the gcc stl)

但是,这种新的风格在新的C ++ 11程序中应该处于首选位置,还是只在需要时才使用?

However, should this new style be preferred everywhere in new C++11-programs, or will it only be used when needed?

就个人而言,我喜欢旧样式,但是混合样式的代码库看起来很丑陋。

Personally, I prefer the old style when possible, but a code-base with mixed styles looks pretty ugly.

推荐答案

在某些情况下,您必须使用尾随返回类型。最值得注意的是,如果指定了lambda返回类型,则必须通过尾随返回类型指定。另外,如果你的返回类型使用一个要求参数名在范围内的 decltype ,那么必须使用尾随的返回类型(但是,通常可以使用<$ c $

There are certain cases where you must use a trailing return type. Most notably, a lambda return type, if specified, must be specified via a trailing return type. Also, if your return type utilizes a decltype that requires that the argument names are in scope, a trailing return type must be used (however, one can usually use declval<T> to work around this latter issue).

尾随返回类型确实有其他一些小的优点。例如,考虑使用传统函数语法的非内联成员函数定义:

The trailing return type does have some other minor advantages. For example, consider a non-inline member function definition using the traditional function syntax:

struct my_awesome_type
{
    typedef std::vector<int> integer_sequence;

    integer_sequence get_integers() const;
}; 

my_awesome_type::integer_sequence my_awesome_type::get_integers() const
{
    // ...
}

成员typedef不在范围内,直到类的名称出现在 :: get_integers 之前,我们必须重复类资格两次。如果我们使用尾随返回类型,我们不需要重复类型的名称:

Member typedefs are not in scope until after the name of the class appears before ::get_integers, so we have to repeat the class qualification twice. If we use a trailing return type, we don't need to repeat the name of the type:

auto my_awesome_type::get_integers() const -> integer_sequence
{
    // ...
}

这个例子,这不是什么大事,但如果你有长类名或类模板的成员函数没有定义内联,那么它可以在可读性方面有很大的不同。

In this example, it's not such a big deal, but if you have long class names or member functions of class templates that are not defined inline, then it can make a big difference in readability.

在C ++ Now 2012的新鲜油漆会议上,Alisdair Meredith如果你使用尾随返回类型一致,所有的函数的名称排列整齐:

In his "Fresh Paint" session at C++Now 2012, Alisdair Meredith pointed out that if you use trailing return types consistently, the names of all of your functions line up neatly:

auto foo() -> int;
auto bar() -> really_long_typedef_name;

我在 CxxReflect ,所以如果你正在寻找一个代码看起来如何使用它们一致的例子,你可以看看那里(例如, 类型)。

I've used trailing return types everywhere in CxxReflect, so if you're looking for an example of how code looks using them consistently, you can take a look there (e.g, the type class).

这篇关于应该返回类型的语法样式是否为新的C ++ 11程序的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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