汽车有什么用
What is the use of auto?
我知道我们可以像这样使用auto
:
auto a = 1;
auto b = Foo(1,2);
或者在函数调用中:
auto foo(){
return Foo(1,2);
}
但是 C++11 还提供了统一的初始化和初始化列表,所以我们可以做到:
Foo a {1,2};
Foo b = {1,2};
Foo foo(){
return {1,2};
}
那么,如果我们已经有大括号语法,auto
有什么用呢?(定义基元类型除外)
我认为当您将auto
与好的迭代器一起使用时,可以看到它的最佳用途。比较:
for (std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it)
自:
for (auto it = vector.begin(); it != vector.end(); ++it)
尽管在 C++11 中,我们有范围可以更好地提供帮助,但迭代器仍然广泛用于您的范围未明确定义或您需要对元素执行操作的情况。
通常,当编译器可以自动推断类型(即要键入的 PITA)时,auto
非常有用。
当返回类型未指定时,您需要 auto。例如,std::bind
.
using namespace std::placeholders;
int n = 7;
auto f1 = std::bind(f, _2, _1, 42, std::cref(n), n);
auto
最适合模板和迭代器。
它不仅可以真正简化语法并提高代码可读性,而且还可以淘汰一些广泛的模板使用。
看看这家伙的页面 - 非常好,切中要害。
简明扼要以下内容:
template <typename BuiltType, typename Builder>
void makeAndProcessObject (const Builder& builder) {
BuiltType val = builder.makeObject();
// ...
}
现在有了auto
,您可以摆脱模板中的多种类型:
template <typename Builder>
void makeAndProcessObject (const Builder& builder)
{
auto val = builder.makeObject();
// ...
}
此外,当您实际调用此函数时,您无需提供任何类型作为模板参数:
MyObjBuilder builder;
makeAndProcessObject(builder);
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 警告处理为错误这里有什么问题
- 什么时候调用组成单元对象的析构函数
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 什么时候在C++中返回常量引用是个好主意
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- C++避免重复声明的语法是什么
- c++库的公共头文件中应该包含什么
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- ifstream什么都没读
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- 这对汽车的用途是什么? - ADL
- 汽车有什么用
- 汽车推断出的那种类型是什么?