C ++ 11 auto 关键字太多了? [英] How much is too much with C++11 auto keyword?

查看:37
本文介绍了C ++ 11 auto 关键字太多了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在 C++11 标准中使用新的 auto 关键字来处理复杂的模板化类型,我相信它就是为此而设计的.但我也将它用于以下方面:

I've been using the new auto keyword available in the C++11 standard for complicated templated types which is what I believe it was designed for. But I'm also using it for things like:

auto foo = std::make_shared<Foo>();

更怀疑:

auto foo = bla(); // where bla() return a shared_ptr<Foo>

我没有看到太多关于这个话题的讨论.似乎 auto 可能被过度使用,因为类型通常是一种文档和完整性检查的形式.在使用 auto 时,您在哪里划清界限?此新功能的推荐用例是什么?

I haven't seen much discussion on this topic. It seems that auto could be overused since a type is often a form of documentation and sanity checks. Where do you draw the line in using auto and what are the recommended use cases for this new feature?

澄清:我不是在寻求哲学观点;我要求标准委员会提供此关键字的预期用途,并可能对如何在实践中实现预期用途发表评论.

To clarify: I'm not asking for a philosophical opinion; I'm asking for the intended use of this keyword by the standard committee, possibly with comments on how that intended use is realized in practice.

推荐答案

我认为应该使用 auto 关键字,每当第一眼很难说出如何编写类型,但是类型表达式右侧的 是显而易见的.例如,使用:

I think that one should use the auto keyword whenever it's hard to say how to write the type at first sight, but the type of the right hand side of an expression is obvious. For example, using:

my_multi_type::nth_index<2>::type::key_type::composite_key_type::
    key_extractor_tuple::tail_type::head_type::result_type

获取boost::multi_index中的复合键类型,即使你知道它是int.你不能只写 int 因为它可以在未来改变.在这种情况下,我会写 auto.

to get the composite key type in boost::multi_index, even though you know that it is int. You can't just write int because it could be changed in the future. I would write auto in this case.

因此,如果 auto 关键字提高了特定情况下的可读性,请使用它.当读者很清楚auto 代表什么类型时,您可以编写auto.

So if the auto keyword improves readability in a particular case then use it. You can write auto when it is obvious to the reader what type auto represents.

以下是一些示例:

auto foo = std::make_shared<Foo>();   // obvious
auto foo = bla();                     // unclear. don't know which type `foo` has

const size_t max_size = 100;
for ( auto x = max_size; x > 0; --x ) // unclear. could lead to the errors
                                      // since max_size is unsigned

std::vector<some_class> v;
for ( auto it = v.begin(); it != v.end(); ++it )
                                      // ok, since I know that `it` has an iterator type
                                      // (don't really care which one in this context)

这篇关于C ++ 11 auto 关键字太多了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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